我有一个看起来像这样的表:
<table id="start" class="appplytblclr">
<tr class="heading">
<td>First coumn</td>
<td>second column</td>
<td>3rd column</td>
<td>4th column</td>
<tr>
<tr id='1'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='2'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='3'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='4'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='5'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='6'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='7'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
</tr>
</table>
我有一个按钮,点击后,应该选择前五个复选框。这是我到目前为止所尝试的:
$('#clickbtn').on('click', function (e) {
var sList = "";
$('input[type=checkbox]').each(function () {
sList += $(this).val() + ",";
});
var comma = sList.split(",", 5);
});
但它似乎不起作用。我该如何处理这个问题?
答案 0 :(得分:4)
$(":checkbox:lt(5)")
如果您担心性能问题(并且您正在使用大型列表),则可以使用效率更高的JavaScript slice
来实现此目的:
$(':checkbox').slice(0, 5)
答案 1 :(得分:3)
您可以使用:lt()选择器:
$("#selectFirstFive").on("click", function() {
var checkBoxes = $("#start tr td :checkbox:lt(5)");//using :lt get first 5 checkboxes
$(checkBoxes).prop("checked", !checkBoxes.prop("checked"));//change checkbox status based on check/uncheck
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="start" class="appplytblclr">
<tr class="heading">
<td>First coumn</td>
<td>second column</td>
<td>3rd column</td>
<td>4th column</td>
<tr>
<tr id='1'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='2'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='3'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='4'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='5'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='6'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
<tr id='7'>
<td>
<input type="checkbox" offval="no" value=" ">
</td>
<td>s</td>
<td>t</td>
<td>f</td>
</tr>
</table>
<input type="button" id="selectFirstFive" value="select" />
&#13;