Javascript jQuery:基于分离标签元素添加属性

Javascript jQuery:基于分离标签元素添加属性,javascript,jquery,Javascript,Jquery,我试图根据复选框标签文本将复选框列表动态标记为“已选中” 以下是一些标记示例: <li class="checkboxlist-item"> <input type="checkbox" id="Categories_24" value="eb9d6610-914b-4e14-99d1-a22200cd5369" name="Categories.SelectedIds" /> <label for="Categories_24">P

我试图根据复选框标签文本将复选框列表动态标记为“已选中”

以下是一些标记示例:

    <li class="checkboxlist-item">
    <input type="checkbox" id="Categories_24" value="eb9d6610-914b-4e14-99d1-a22200cd5369" name="Categories.SelectedIds"  />
    <label for="Categories_24">Properties &amp; Moving</label>
</li>
  • 物业及;移动
  • 因此,如果标签文本是“Properties&Moving”,我想在这里将输入元素标记为“checked”


    非常感谢您的帮助-谢谢

    您可以使用
    .each()
    方法循环检查每个复选框。然后使用
    .next()
    ,您可以找到该元素旁边的label元素

    $("input[type=checkbox]").each(function(){
    if($(this).next().text()=="Properties & Moving")
    {
        $(this).prop("checked",true);
    }
    });
    
    试试这个:

    $('label:contains(Properties & Moving)').siblings(':checkbox').prop('checked', true);
    
    首先通过查找标签文本 if($(“标签”).text()=“属性和移动”) 然后添加选中的代码 如checked=“checked”

    我会使用,因此您可以确定确切的字符串:

    演示:


    你试过什么吗?分享你的代码或自己做一些研究。
    if( $('.checkboxlist-item label').text() == 'Properties Moving' )
     $('.checkboxlist-item input').prop('checked', true);
    
    $(".checkboxlist-item label").filter(function() {
        return $(this).text() === "Properties & Moving";
    }).siblings(":checkbox").prop("checked", true);
    
    $("input:checkbox").each(function(){
    if($('label[for=' + this.id + ']').html()=="Properties &amp; Moving")
    {
        $(this).prop("checked", true);
    }
    });
    
    $('label').each(function(){
        if($(this).html()=='Properties &amp; Moving'){
            $(this).siblings(':checkbox').prop('checked', true);
        }
    });