我为如下函数构建了一个jQuery选择器:
$('html').not('.table-main tr[selected]').mousedown( function( e ) {
但不知怎么的,它根本没有过滤,我不太明白为什么。即使我只为选择器留下('.tablemain'),我在点击表时仍然会触发函数。。。这是怎么回事?
使用document或'body'而不是'html' 编辑:只是试着在桌子外面使用另一个块,它就起作用了。我有可能不能在桌子上用这个吗? Update2:根据请求,这里是表的html代码: <table border="0" cellspacing="2px" cellpadding="5px" class="table-main">
<tr id="tablefields">
<th style="padding: 0;">
<table cellpadding="0" cellspacing="0" border="0" align="center">
<tr><th><div class="tr-head-get" id="tr-get-0">Name</div></th></tr>
<tr><th><div class="th-header" id="th-header-0" style="top: 54px;">Name</div></th></tr>
</table>
</th>
<th style="padding: 0;"></th>
</tr>
<tr id='table_form_new_device' class='table_form_class'>
<form accept-charset="UTF-8" action="/devices" class="new_device" data-remote="true" id="new_device" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="T2dSeZpxxvgJdTP+yoE7BrVODzqJ95gyVu9Wh/v7oP8=" /></div>
<th class='tablefield'>
<input id="device_devicename" name="device[devicename]" size="10" type="text" />
</th>
<th>
<div class='submitbox' id='submitbox_new_device'>S</div>
<script>
$('#submitbox_new_device').click(function (event) {
$('#new_device').submit();
});
</script>
</th>
</form></tr>
</table>
<div class="dropdown-button" style="margin: 0 2px;">Filter</div>
您真的非常想使用委托事件处理,因为您不想将事件处理程序附加到文档中的每个元素。您希望在文档级别截获冒泡事件,只需检查mousedown是否来自表中非选定行的元素。
此外,tr[selected]
似乎不太可能工作。我认为您需要向所选行添加一个类"selected"
,然后使用tr.selected
作为选择器。
如果你做出这样的改变,我建议你选择以下两种选择之一:
$(document).mousedown(function(e) {
if (!$(e.target).is('.table-main tr.selected')) {
// mouse down and it wasn't in a selected row of your table)
}
})
您还可以让jQuery委派做更多的工作:
$(document).on('mousedown', ':not(.table-main tr.selected)', function() {
// mouse down and it wasn't in a selected row of your table)
});
在看到实际的HTML之后,如果我正确地理解了问题,这应该是可行的。只要单击不在具有selected
类的table-main
行中,只要单击发生,就会给您一个事件:
$(document).on('mousedown', function(e) {
// mouse down and it wasn't in a selected row of your table)
e.stopPropagation();
if (!$(e.target).closest(".table-main tr.selected").length) {
console.log("mousedown not in selected row of table-main")
}
});
下面是一个演示:http://jsfiddle.net/jfriend00/5QD6N/
在类型为tr
的元素上使用[selected]
毫无意义。您使用选定的输入(checkbox,radio
)。您可以将类.selected
添加到.table-main
中的tr元素中,然后使用:
编辑:就像上面发布的人一样,你想使用select来选择嵌套在主体内的元素。
$('body').find(':not(.selected)').mousedown(function(e){})
$('html')
创建一个包含HTML元素的jQuery对象。
.not('.table-main tr[selected]')
删除具有选定属性(此处有错误,该属性不会出现在TR上)的任何TR元素,这些元素是table-main
类成员的元素的后代。由于HTML元素不是TR元素,不能从任何东西派生而来,因此这不会删除任何元素,也不会产生任何效果。
mousedown( function( e )
将事件处理程序绑定到HTML元素。除非有什么东西停止传播,否则任何点击最终都会出现在那里。
我猜(因为你实际上没有说你想实现什么)你想捕捉未选中的TR元素上的点击。假设您切换到使用类来使HTML有效…
$('.table-main tr:not(.selected)').mousedown(…);
和
<tr class="selected">