Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

Jquery click function not being called

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

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.

The same code posted here

$('.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');
});

Again, this is a very basic example and a toggle class will not be possible for what I am using this for.

Any help would be awesome!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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');
});

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');
    }
});

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 Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...