Javascript 单选按钮上的 jQuery .change()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2644437/
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() on Radio Button
提问by Denis Hoctor
I must be missing something obvious here... I can't get .change()to fire on radio buttons? I have the code below live here!
我一定在这里遗漏了一些明显的东西......我无法让.change()在单选按钮上触发?我有下面的代码住在这里!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Radio Button jQuery Change</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
console.log("parsed");
$("input[name='rdio']").change(function() {
console.log("changed");
if ($("input[name='rdio']:checked").val() == 'a')
$("output").text("a changed");
else if ($("input[name='rdio']:checked").val() == 'b')
$("output").text("b changed");
else
$("output").text("c changed");
});
</script>
</head>
<body>
<div>
<input type="radio" name="rdio" value="a" checked="checked" /> a <br/>
<input type="radio" name="rdio" value="b" /> b <br/>
<input type="radio" name="rdio" value="c" /> c
</div>
<h3>Output:</h3>
<div id="output"></div>
</body>
</html>
Can anyone see what I've missed?
谁能看到我错过了什么?
Thanks, Denis
谢谢,丹尼斯
回答by Mickel
You must put the code inside the dom-ready event...
您必须将代码放在 dom-ready 事件中...
$(document).ready(function(){
// Your code here
});
or else the script gets executed before the HTML-elements have been loaded. Thus, no radioboxes exist.
否则脚本会在加载 HTML 元素之前执行。因此,不存在radioboxes。
回答by Shervin Asgari
Your
您的
$("output").text("a changed");
should also be
也应该
$("#output").text("a changed");
because it is an id you are matching against.
因为它是您要匹配的 ID。

