Events on dynamically added classes

北慕城南 提交于 2019-12-20 07:26:40

问题


I have a form where the class of the button is dynamically changing, depending up where the request is coming from. I am trying to capture the onclick event, but it does not take in the dynamically added class. I made sure that the class is being added to the button. Where can I be going wrong.

Snippets --

   $('.button').removeClass('oldClass');
   $('.button').addClass('newClass');

   <button class = "button">Button</button>

OnClick --

     $('.newClass').click(function(){
          alert("test");
     });

The code does not get to this event event though the button class is changed to newClass.

Thanks


回答1:


Thats cause when you bind the click event the element has another class.

Try somesthing like this:

$('body').on('click', '.newClass', function () {
        alert('test');
    });

Example




回答2:


Setting event handlers through methods like .bind (or shortcuts like .click) are only set for elements that currently match the selector. If you want to set up the event handler for elements that currently match as well as all future matches then you should use .on.




回答3:


You can try adding the click functionality directly to the button when the DOM loads, and just use .hasClass() to check if the newClass has been applied or not.

$('.button').click(function() {
    if($(this).hasClass('newClass')) {
        //Code for new class click
        alert('test');
    }
});

JSFiddle: http://jsfiddle.net/yRySK/1/




回答4:


I fixed the problem using the delegate method provided by JQuery.

$('body').delegate('.newClass','click', delegatefunction);

function hasClass() {
   alert("Hello!!");
}

Thanks for the help.



来源:https://stackoverflow.com/questions/18366366/events-on-dynamically-added-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!