Javascript jQuery change() 和 bind("change") 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12224852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery change() and bind("change") do not work
提问by Zeeshan
This question has already been asked but I am stuck with the most basic level of it. I haven't added anything to my html except a select tag and trying to catch the change event by jquery. Here is my code:
这个问题已经被问到,但我坚持最基本的水平。除了选择标记并尝试通过 jquery 捕获更改事件之外,我没有在我的 html 中添加任何内容。这是我的代码:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
$('#target').bind("change", function{
alert('Changed');
});
</script>
</head>
<body>
<form>
<select id="target">
<option value="option1" selected="selected">Option 1</option>
<option value="option2">Option 2</option>
</select>
</form>
</body>
Even the change() function does not work.
甚至 change() 函数也不起作用。
<script>
$('#target').change(function() {
alert('Changed');
});
</script>
Please help me figure out where I am doing wrong. In one of the similar problems on Stackoverflow, I got http://jsfiddle.net/78x9Q/4/as an answer. But even an exact copy paste of that code is not working for me.
请帮我弄清楚我做错了什么。在 Stackoverflow 上的一个类似问题中,我得到了http://jsfiddle.net/78x9Q/4/作为答案。但即使是该代码的精确复制粘贴也不适合我。
P.S.: jQuery is loading as I tested it and found working using this:
PS:jQuery 正在加载,因为我测试了它并发现它可以使用:
<script>
$(function() {
alert('Changed');
});
</script>
回答by Danil Speransky
Your code does not work because you try to work with dom when it is not built yet. Use this:
您的代码不起作用,因为您在尚未构建 dom 时尝试使用它。用这个:
$(document).ready(function () {
// your code
});
Then your code will run when dom is already built.
然后你的代码将在 dom 已经构建时运行。
回答by Lucas Green
This:
这个:
<script>
$('#target').change(function() {
alert('Changed');
});
</script>
Ought to be this:
应该是这样的:
<script>
$(function () {
$('#target').change(function() {
alert('Changed');
});
});
</script>
Meaning you are executing your bindings before the document is ready.
这意味着您正在文档准备好之前执行绑定。
回答by rahul
use it like this
像这样使用它
$(document).ready(function () {
$('#target').change(function() {
alert('Changed');
});
});
回答by Hazem Salama
You need to wrap your jquery code inside document ready event
您需要将 jquery 代码包装在文档就绪事件中