jQuery的点击功能没有被调用 [英] Jquery click function not being called

查看:102
本文介绍了jQuery的点击功能没有被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个小问题,我敢肯定我确实缺少一些小东西,但是我发誓我会发疯.

This is kind of an off little issue and I am sure I'm missing something really small, but I swear I am going crazy.

我有一个按钮,我试图在该按钮上添加和删除一个类,并且该按钮正在运行,但是一旦我尝试用该新类调用另一个函数,该函数就会静默失败.我不知道为什么这会无声地失败,并且非常希望它能正常工作

I have a button that I am trying to add and remove a class on and that is working, but as soon as I try and call another function with that new class the function just failed silently. I do not know why this is failing silently and would very much like it to work

这里是我正在使用的jsFiddle ,它与我的工作方式极为相似使用它.因此,乍一看,看来我可以做一个切换类,但是不可能将所有其他代码都放在其中.

Here is a jsFiddle I'm working with, it is extremely stripped down from what I am using it for. So on initial glance it looks like I can do a toggle class, but with all my other code in there it is just not possible.

此处发布的相同代码

$('.holdProject').on('click', function(){

    $('.holdProject').addClass('resumeProject');
    $('.holdProject').removeClass('holdProject');
    console.log('here');
});    

$('.resumeProject').on('click', function(){
  $('.resumeProject').addClass('holdProject');
  $('.resumeProject').removeClass('resumeProject');
  console.log('there');
});

同样,这是一个非常基本的示例,我无法将其用于我的切换类.

任何帮助都会很棒!

推荐答案

由于DOMReady上不存在.resumeProject元素,因此需要委托click函数.您可以通过将选择器传递给 on() 函数来实现此目的:

You need delegate the click function, since no .resumeProject elements exist on DOMReady. You can achieve this by passing in a selector to the on() function:

$(document).on('click', '.resumeProject', function() {
    $(this).addClass('resumeProject').removeClass('holdProject');
});

此外,您可以使用 is() :

In addition, you could easily combine the two handlers using is():

$(document).on('click', '.resumeProject,.holdProject', function() { 
    if($(this).is('.resumeProject'))
    {
        $(this).addClass('holdProject').removeClass('resumeProject');
    }
    else
    {
        $(this).addClass('resumeProject').removeClass('holdProject');
    }
});

当然,最好缩小委托的范围,以便将事件绑定到最近的静态父元素.由于我们不了解上下文或HTML,因此很难确定您的情况.

It is always better of course, to narrow down the delegation, so that the event should be bound to the nearest static parent element. Since we don't know the context or HTML, it's difficult to say for certain what that is in your case.

jsFiddle演示

这篇关于jQuery的点击功能没有被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆