为什么函数不会输出到这个jQuery选择器中

Why won't function output into this jQuery selector?

本文关键字:jQuery 选择器 函数 输出 为什么      更新时间:2023-09-26

我希望这是我做过的愚蠢的事情。我在底部附近得到了一个函数 unigref,它(我相信)输出一个字符串。但是,当我调用函数来构建 jQuery 选择器时,我无法让它正常工作。我知道其他一切都有效,因为当我使用静态字符串时,单选按钮被选中。

这是我的jsfiddle/9Edxx。请帮忙。

var checkCount = 0;
var maxChecks = 2;
$(document).ready(function() {
$("#test").click(function() {
    alert($(':checked').length);
});
$(':checkbox[name=checkbox]').change(function() {

    checkCount = $(':checkbox:checked').length;
    if (checkCount >= maxChecks) {
      $(':checkbox[name=checkbox]').not(':checked').attr('disabled', true);  
        $(":radio[value="+uniqref()+"]").prop('checked', true);

    } else {
      $(':checkbox[name=checkbox]:disabled').attr('disabled', false);
    }
    if (this.checked) {
        $("td.label").append("<label>" + this.value + "</label>");
    } else {
        $("td.label").find(":contains('" + this.value + "')").remove();
    }
});
$('#button').click(function() {
    alert(uniqref());
});

function uniqref() {
    return $("td.label").text().split('').sort().join('').replace(/'s/g, "");
}

});​

更新:错别字是正确的,但问题仍然存在。

http://jsfiddle.net/9Edxx/

是的,这真的很愚蠢:这只是一个错字。

$(":radio[value="+unigref()+"]").prop('checked', true);

应该是

$(":radio[value="+uniqref()+"]").prop('checked', true);

使用小写Q而不是G.


另外,你在实际更新 td.label 的值之前调用 uniqref()。

应按以下顺序排列:

if (this.checked) {            
    // ...
}
if (checkCount >= maxChecks) {            
    // ...
}

http://jsfiddle.net/7mvmT/7/

http://jsfiddle.net/7mvmT/6/

基本上这一行:

$(":radio[value="+uniqref()+"]").prop('checked', true);

过早调用(在实际选中复选框之前。一个简单而丑陋的黑客:

setTimeout(function(next) {               
     $(":radio[value="+uniqref()+"]").prop('checked', true);    
}, 0);

解决了它。

正如Niko提到的,你还有一个错字。

不需要黑客攻击。http://jsfiddle.net/dn7gM/

PS:仅适用于 2 个前无线电,因为并非所有 ID 都设置正确 ;-)