为什么这个jQuery输入选择器需要一个过滤器解决方法

时间:2012-07-26 06:22:31

标签: jquery

以下行这在我的firefox / firebug代码中不起作用(但在JSFIDDLE中工作正常),你会在下面看到我有一个解决方法,只是想知道是否有人知道内部原因?

var checkedVal = parseInt($('input[@name=' + uniqueNamePart + 'currDim]:checked').val(), 10);

http://jsfiddle.net/darrenshrwd/eqh2y/43/

<input type="radio" value="1" name="blahcurrDim">One
<input type="radio" checked="" value="2" name="blahcurrDim">Two
<input type="radio" value="3" name="blahcurrDim">Three
<input type="radio" value="4" name="blahcurrDim">Four

...

$('document').ready(

function() {

    var uniqueNamePart = "blah";

    var dimensionClick = function() {

        // This does NOT work in my code in firefox/firebug (but works fine in JSFIDDLE):
        var checkedVal = parseInt($('input[@name=' + uniqueNamePart + 'currDim]:checked').val(), 10);

        // This does work in both:
        //var myRadio = $('input[name=' + uniqueNamePart  + 'currDim]'),
        //    checkedVal = parseInt(myRadio.filter(':checked').val(), 10);        

        alert(checkedVal);

    };

    $('input[name=' + uniqueNamePart + 'currDim]:radio').click(dimensionClick);

});

1 个答案:

答案 0 :(得分:3)

您的attribute selector格式错误。不需要@个字符:

var checkedVal
    = parseInt($('input[name=' + uniqueNamePart + 'currDim]:checked').val(), 10);

该代码似乎在您的小提琴中起作用,但这是因为唯一的<input>元素是单选按钮,因此即使忽略无效的属性选择器,匹配也会成功。