jquery 使用 .not() 选择
我在使用 jQuery 时遇到了一些麻烦。 我有一组带有 .square 类的 Div。其中只有一个应该有 .active 类。该 .active 类可以在单击时激活/取消激活。
这是我的代码:
jQuery().ready(function() {
$(".square").not(".active").click(function() {
//initialize
$('.square').removeClass('active');
//activation
$(this).addClass('active');
// some action here...
});
$('.square.active').click(function() {
$(this).removeClass('active');
});
});
我的问题是,即使我单击活动的 .square,第一个函数 si 也会调用,就好像选择器不起作用一样。事实上,这似乎是由于 addClass('active') 行...
您知道如何解决这个问题吗? 谢谢
I have some troubles with jQuery.
I have a set of Divs with .square classes. Only one of them is supposed to have an .active class. This .active class may be activated/de-activated onClick.
Here is my code :
jQuery().ready(function() {
$(".square").not(".active").click(function() {
//initialize
$('.square').removeClass('active');
//activation
$(this).addClass('active');
// some action here...
});
$('.square.active').click(function() {
$(this).removeClass('active');
});
});
My problem is that the first function si called, even if I click on an active .square, as if the selector was not working. In fact, this seems to be due to the addClass('active') line...
Would you have an idea how to fix this ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只是为了给出与其他答案不同的东西。 Lonesomeday 的说法是正确的,函数与一开始的任何内容都绑定在一起。这不会改变。
以下代码使用 jQuery 的 live 方法来掌握最新情况。 Live 将始终处理选择器引用的任何内容,因此如果您更改类,它会不断更新。您还可以使用
square
类动态添加新的 div,它们也会自动具有处理程序。示例工作: http://jsfiddle.net/jonathon/mxY3Y/
注意:我不是说这就是我的做法(完全取决于您的要求),但这只是另一种看待事物的方式。
Just to give something different from the other answers. Lonesomeday is correct in saying the function is bound to whatever they are at the start. This doesn't change.
The following code uses the live method of jQuery to keep on top of things. Live will always handle whatever the selector is referencing so it continually updates if you change your class. You can also dynamically add new divs with the
square
class and they will automatically have the handler too.Example working: http://jsfiddle.net/jonathon/mxY3Y/
Note: I'm not saying this is how I would do it (depends exactly on your requirement) but it is just another way to look at things.
这是因为该函数绑定到创建元素时不具有
active
类的元素。您应该绑定到所有.square
元素,并根据该元素是否具有active
类来采取不同的操作:This is because the function is bound to elements that don't have the
active
class when you create them. You should bind to all.square
elements and take differing actions depending on whether the element has the classactive
: