Javascript jQuery:是否选中与可见列同名的复选框?

Javascript jQuery:是否选中与可见列同名的复选框?,javascript,jquery,Javascript,Jquery,我想使用jQuery使用表单元格的类名来选中相应值的复选框。我不知道我是否需要使用eval或类似的东西 代码: <p style="float:right;"> These columns are visible: <br/><input type="checkbox" name="vehicle" value="col1" /> Col1 <br/><input type="checkbox" name="vehicle" value="

我想使用jQuery使用表单元格的类名来选中相应值的复选框。我不知道我是否需要使用eval或类似的东西

代码:

<p style="float:right;">
These columns are visible: 
<br/><input type="checkbox" name="vehicle" value="col1" /> Col1
<br/><input type="checkbox" name="vehicle" value="col2" /> Col2
<br/><input type="checkbox" name="vehicle" value="col3" /> Col3
</p>
<table id="comptable">
<tr> 
<td class="col1">Col1</td>
<td class="col2" style="display:none;">Col2</td>
<td class="col3">Col3</td>
</tr>
</table>
$(document).ready(function(){
    var visible_tds = $('comptable td:visible');
    // Check the checkboxes that correspond to the visible table cells.
    $.each(visible_tds, function() { 
       // use ($(this).attr('class'))
       // to check the checkbox?
    });
});

jsIDLE:

您可以这样做:

$(document).ready(function(){
    // Check the checkboxes that correspond to the visible ones
    $('#comptable td:visible').each(function() { 
        $("input[value='" + $(this).attr('class') + "']").attr('checked', true);
    });
});
input[value=]选择器将返回属性值与标记之间指定的内容相匹配的任何输入


从兼容选择器的开始,您还缺少一个。该表的ID为Compatible,因此要选择一个ID,您必须在其前面加上一个。

您可以这样做:

$(document).ready(function(){
    // Check the checkboxes that correspond to the visible ones
    $('#comptable td:visible').each(function() { 
        $("input[value='" + $(this).attr('class') + "']").attr('checked', true);
    });
});
$(document).ready(function(){
    $('#comptable td:visible').each(function() {
       $("input[type=checkbox][value='" + $(this).attr("class") + "']").prop("checked", true);
    });
});
input[value=]选择器将返回属性值与标记之间指定的内容相匹配的任何输入

从兼容选择器的开始,您还缺少一个。该表的ID为Compatible,因此要选择一个ID,必须在其前面加上

$(document).ready(function(){
    $('#comptable td:visible').each(function() {
       $("input[type=checkbox][value='" + $(this).attr("class") + "']").prop("checked", true);
    });
});
这应该能奏效。它找到值等于每个可见td的class属性值的复选框,并将checked属性设置为true。注意,至少要使用jQuery 1.6才能使用prop函数,否则,必须使用attr

你可以看到它在运行

这应该能奏效。它找到值等于每个可见td的class属性值的复选框,并将checked属性设置为true。注意,至少要使用jQuery 1.6才能使用prop函数,否则,必须使用attr

你可以看到它在运行