[英]How to exclude an element from jquery function?
when a table is being hovered, I have a function that adds a certain class to some element. 当表格被悬停时,我有一个函数可以将某个类添加到某些元素中。
In that table, I want this behavior for all elements except one. 在该表中,我希望除一个元素外的所有元素都具有此行为。
therefore in the code, I included th,td,td span,td p,td div.good
, 因此,在代码中,我包括了
th,td,td span,td p,td div.good
,
But - I have a specific span ( <span class="foo">
) inside the table which I want to exclude, how can I do it? 但是-我要排除在表中的特定范围(
<span class="foo">
),我该怎么做?
(I'm not a JS coder so after looking in previous q's, still not sure about the most recommended way to do this in my context) (我不是JS编码器,因此在查看以前的q后,仍然不确定在我的上下文中最推荐的方式)
Code: 码:
<script>
$(document).ready(function(){
$(function(){
$('th,td,td span,td p,td div.good').mouseenter(function(){
$(".light").addClass('altbg')
}).mouseout(function(){
$(".light").removeClass('altbg')
});
});
})
</script>
Although it's possible to use .not()
to exclude a set of elements from an existing selector, arguably your code is inefficient because it registers the two event handlers against a large set of elements and the callbacks will be invoked repeatedly as you move your mouse around the table. 尽管可以使用
.not()
从现有选择器中排除一组元素,但是可以说您的代码效率低下,因为它针对大量元素注册了两个事件处理程序,并且在您移动鼠标时会重复调用回调桌子周围。
Consider this, instead: 考虑一下,改为:
$('table,.foo').on('mouseenter mouseleave', function (e) {
$('.light').toggleClass('altbg');
});
There are only two elements listening for the mouse events - the table itself, and the span you wish to ignore. 只有两个元素在监听鼠标事件-表本身和您要忽略的范围。 Since you cannot reach the inner span without crossing the table this will produce the desired effect.
由于您不能不跨桌子就无法到达内部跨度,这将产生所需的效果。
See http://jsfiddle.net/alnitak/eecqkx6v/ 参见http://jsfiddle.net/alnitak/eecqkx6v/
Use the jquery .not
method to exclude elements 使用jquery
.not
方法排除元素
$('th,td,td span,td p,td div.good').not(".foo")
jQuery .not documentation jQuery .not文档
Also you do not have to use both the .ready
method along with the passing a function to $()
they will do the same thing. 同样,您不必同时使用
.ready
方法和将函数传递给$()
它们将执行相同的操作。
$(function(){
$('th,td,td span,td p,td div.good').not(".foo").mouseenter(function(){
$(".light").addClass('altbg')
}).mouseout(function(){
$(".light").removeClass('altbg')
});
});
is all you need 是你所需要的全部
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.