Events on dynamically added classes

前端 未结 4 1933
逝去的感伤
逝去的感伤 2021-01-27 11:39

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 tak

相关标签:
4条回答
  • 2021-01-27 12:00

    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/

    0 讨论(0)
  • 2021-01-27 12:01

    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

    0 讨论(0)
  • 2021-01-27 12:07

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

    $('body').delegate('.newClass','click', delegatefunction);
    
    function hasClass() {
       alert("Hello!!");
    }
    

    Thanks for the help.

    0 讨论(0)
  • 2021-01-27 12:13

    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.

    0 讨论(0)
提交回复
热议问题