根据复选框JQuery设置标签值

根据复选框JQuery设置标签值,jquery,attr,Jquery,Attr,我只是想根据复选框的change()事件设置一个labels值。我的复选框和标签代码为 <div class="Sell" style="width: 47px;"><input type="checkbox" id="chkSell" class="_1"/></div> <div class="BuySelllbl" style="width: 10px;"><label id="lblBuySell_1"></label&g

我只是想根据复选框的change()事件设置一个labels值。我的复选框和标签代码为

<div class="Sell" style="width: 47px;"><input type="checkbox" id="chkSell" class="_1"/></div>
<div class="BuySelllbl" style="width: 10px;"><label id="lblBuySell_1"></label></div>
警报每次都输出正确的标签id,但在.attr属性中未设置任何内容。我的语法有错误吗?任何帮助都很好。 非常感谢。
NickG

您需要更改验证复选框是否已选中的方式

// First method - Recommended
$('#checkbox').prop('checked')  // Boolean true

// Second method - Makes code more readable (e.g. in if statements)
$('#checkbox').is(':checked')  // Boolean true

// Third method - Selecting the checkbox & filtering by :checked selector
$('#checkbox:checked').length  // Integer >0
$('#checkbox:checked').size()  // .size() can be used instead of .length

// Fourth method - Getting DOM object reference
$('#checkbox').get(0).checked  // Boolean true
$('#checkbox')[0].checked      // Boolean true (same as above)

属性值没有label的任何值,应替换以下内容的语句:

$("#chkSell").live('change',function(){
    var y = $(this).attr("class");
    var x = "#lblBuySell" + y;  
    alert(x);
    if(this.checked){       
        $(x).html("S");
        $(x).attr("style","color: red;");
    }else{
        $(x).removeAttr("value");
    }
可以使用长度变量检查是否未选择任何图元

x.length

谢谢@Markus我真的很感激,我不知道这个值不会被接受,inline不是属性值吗?属性值只适用于输入类型。标签它是一个结构,所以你要在它里面添加一些东西,这就是为什么你必须使用html方法。作为提示,您可以使用其他答案中提到的css方法$(x) .html('S').css('color','red');
$("#chkSell").live('change',function(){
    var x = $("#lblBuySell." + $(this).attr("class"));  

    if(this.checked == true)
    {
        x.attr("value","S");
        x.attr("style","color: red;");
    }
    else
        x.removeAttr("value");
});
x.length