使用jQuery的asp中的单选按钮

时间:2014-03-31 22:08:49

标签: jquery radio-button

这有效:

<script>
    $("input:radio").change(function () {
        alert($(this).attr("name"));
    });
</script>

结果是:ctl00 $ ctl00 $ cphBody $ cphBody $ RS_rbtItemGroup

但这不起作用:

<script>
    $("input[name=ctl00$ctl00$cphBody$cphBody$RS_rbtItemGroup]:radio").change(function () {
        alert($(this).attr("name"));
    });
</script>

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

因为名称中包含“$”,所以需要在名称查询中添加单引号。试试这个:

<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
    $(document).ready(function() {
        $("input[name='ctl00$ctl00$cphBody$cphBody$RS_rbtItemGroup']:radio").change(function () {
            alert($(this).attr("name"));
        });
    });
</script>
</head>
<body>
    <input type='radio' name='ctl00$ctl00$cphBody$cphBody$RS_rbtItemGroup' value='yes'>Yes</input>
    <input type='radio' name='ctl00$ctl00$cphBody$cphBody$RS_rbtItemGroup' value='no'>No</input>
</body>
</html>

答案 1 :(得分:1)

jQuery API表示属性等于选择器需要an unquoted single word or a quoted string。不幸的是,它将$字符视为非单词字符,因此您必须将您的名称属性值放在引号中:

<script>
    $("input[name='ctl00$ctl00$cphBody$cphBody$RS_rbtItemGroup']:radio").change(function () {
        alert($(this).attr("name"));
    });
</script>

但是,我建议您实际使用attribute ends with selector,因为您姓名的第一部分是generated by .NET,如果您调整布局,可能会有所改变:

<script>
    $("input[name$='$RS_rbtItemGroup']:radio").change(function () {
        alert($(this).attr("name"));
    });
</script>