[英]Jquery Event Handler “.on()”
I have a problem with the Jquery Event Handler ".on()". 我对Jquery事件处理程序“ .on()”有问题。
I have a button Favorite on my post on my home page. 我主页上的帖子上有一个收藏夹按钮。
If you haven't favorited the post: 如果您不喜欢该帖子:
If you have favorited the post: 如果您喜欢该帖子:
Why when I click multiple times (>1) on this button, my script does the same method (Event) whereas I have my class .active on my li or not? 为什么当我点击多次(> 1)在此按钮上,我的脚本做同样的方法(事件),而我有我的课。主动对我李与否?
It's like .on() doesn't manage dynamic class change... 就像.on()不能管理动态的类更改...
My HTML: 我的HTML:
<ul class="post-list">
<li>
<a href="#" class="favorite">Favorite</a>
</li>
<li class="active">
<a href="#" class="favorite">Favorite</a>
</li>
</ul>
My Jquery: 我的Jquery:
$(function(){
$('.post-list li.active .favorite').on('click', function(e){
e.preventDefault;
// Event 2
});
$('.post-list li:not(.active) .favorite').bind('click', function(e){
e.preventDefault;
// Event 1
});
});
jQuery binds the events to the result of your selectors ( once ). jQuery将事件绑定到选择器的结果( 一次 )。 You are hoping that the selector is re-computed each time the event fires, but at that point the handlers have already been bound to whichever elements matched your selector originally.
您希望每次事件触发时都会重新计算选择器,但那时处理程序已经绑定到最初与选择器匹配的任何元素。
try: 尝试:
$(function(){
$('.post-list li .favorite').on('click', function(e){
e.preventDefault();
if (e.target.hasClass('active') {
//Event 2
}
else {
//Event 1
}
});
});
Your scripts once searches li.active
elements and adds handlers to them (Event 2) and once time searches li:not(.active)
elements and adds handlers to them (Event 1). 您的脚本一次搜索
li.active
元素并向其添加处理程序(事件2),一次搜索li:not(.active)
元素并向其添加处理程序(事件1)。
You have 2 ways to solve that problem: 您有两种方法可以解决该问题:
Example of second way: (take a look at second .on()
function argument and also at selector) 第二种方法的示例:(看看第二个
.on()
函数参数以及选择器)
$(function(){
$('.post-list').on('click','li.active .favorite' function(e){
e.preventDefault;
// Event 2
});
$('.post-list').bind('click','li:not(.active) .favorite' function(e){
e.preventDefault;
// Event 1
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.