我需要一个选择器,其中包含:
Any table cell that has a checkbox in it
现在,我正在使用:
$('td input').filter(':checkbox').each(function() {
$(this).closest('td').addClass('CursorPointer');
});
$('td.CursorPointer').on('click',function() {
$('input:checkbox',this).click();
});
它有效,但可能不是“最好的”。
最佳答案
使用the :has()
selector或the has()
method :
// select all <td> elements that have a checkbox in them
$('td:has(input:checkbox)');
// same effect
$('td').has('input:checkbox');
请注意input:checkbox
相当于 Sizzle/jQuery 中的 input[type="checkbox"]
。
您的代码示例可以重写为:
$('td:has(input:checkbox)').on('click', function() {
$('input:checkbox', this).click();
});
或者……
$('td').has('input:checkbox').on('click', function() {
$('input:checkbox', this).click();
});
请注意,.has()
比 :has
更高效:http://jsperf.com/jquery-has-vs-has虽然 :has()
恕我直言,可读性稍高一些。
关于jquery - jQuery 中需要一个 "HAS A"选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9301459/