jQuery更改事件在页面加载时触发输入
当文档在浏览器中准备就绪时,为什么以下 JQuery
触发的事件正在运行.我对 JQuery
的经验很少,所以我对此很执着.
Why is the following JQuery
triggered event running when the document becomes ready in the browser. I have very little experience with JQuery
so I am kinda stuck with this one.
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<form name="f1" id="f1">Input:
<input list="br" name="b" id="b">
<datalist id="br">
<option value="10">
<option value="11">
<option value="12">
<option value="100">
<option value="101">
</datalist>
</form>
<br>
<fieldset>
<legend id="result"></legend>
</fieldset>
<script>
$("#b")
.change(function () {
var str = $('#b').val();
$("#result").text(str);
$.get("cgi-bin/something.cgi?s=" + str, function (data) {
$("body")
.append("Name: " + data.name)
.append("Time: " + data.time);
}, "json");
alert("Load was performed.");
})
.change();
</script>
如果您还可以告诉我,为什么要指出"cgi-bin/something.cgi?s ="+ str为什么在 Get
请求中不包含var str
的原因呢?预先感谢您的帮助.
Bonus points if you can also tell me why "cgi-bin/something.cgi?s=" + str is not including var str
in the Get
request. Thanks in advance for the help.
change()
事件是在加载时触发的,因为它是在没有参数的情况下调用的.您的代码的极为简化的版本如下所示:
The change()
event is triggered on load because it's being called without an argument. An extremely simplified version of your code looks like this:
$("#b").change(function(){ /*do stuff*/ }).change();
这可能会造成混淆,因为 change()
函数充当处理程序或触发器,具体取决于传递参数的方式(请参阅文档
This can be confusing because the change()
function acts as either a handler or a trigger, depending on how an argument is passed (see docs here).
只需删除多余的 change()
调用即可解决问题.
Simply removing the extra change()
call should do the trick.