javascript传递变量到文本输入onchange事件不起作用

时间:2017-09-07 17:31:32

标签: javascript html

我尝试使用网址参数填充文字输入:http://127.0.0.1/index.html?uname="john"

<p class="control">
<input autofocus id="uname" class="input" 
  onchange="(sayhello(this.value))" 
  oninput="sayhello(this.value)" 
  placeholder="Enter your name" type="text">
</p>

我使用以下脚本将URL参数传递给文本输入,但事件不起作用,只有在我删除输入文本并键入它时它们才有效。

<script>
var uunme = window.location.href.match(/\?uname=(.*)/);
document.getElementById("uname").value = uunme[1];

</script>

1 个答案:

答案 0 :(得分:0)

这样的事情?

var url_string = "https://example.com/?uname=foo"; // window.location.href
var url = new URL(url_string);
var uunme = url.searchParams.get("uname");
document.getElementById("uname").value = uunme;

function sayhello(text) {
  alert(text);
}
<p class="control">
  <input autofocus id="uname" class="input" onchange="sayhello(this.value);" oninput="sayhello(this.value);" placeholder="Enter your name" type="text">
</p>

我使用Stackoverflow问题“How to get the value from the GET parameters?”中的答案来可靠地检索URL参数uname。我还整理了一些东西。