单选按钮上的jQuery .change()

时间:2010-04-15 10:25:39

标签: javascript jquery input

我必须在这里遗漏一些明显的东西......我无法在单选按钮上触发.change()?我的代码如下here

<!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>

任何人都能看到我错过的东西吗?

谢谢, 丹尼斯

2 个答案:

答案 0 :(得分:42)

您必须将代码放在dom-ready事件中......

 $(document).ready(function(){
   // Your code here
 });

或者在加载HTML元素之前执行脚本。因此,不存在放射性物质。

答案 1 :(得分:16)

你的

$("output").text("a changed");

也应该是

$("#output").text("a changed");

因为它是您要匹配的ID。

相关问题