动态添加类的事件 [英] Events on dynamically added classes

查看:77
本文介绍了动态添加类的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个窗体,按钮的类别是动态变化的,这取决于请求的来源。我试图捕获onclick事件,但它并不占用动态添加的类。我确定该类被添加到按钮。我可以在哪里出错。



片段 -

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

< button class =button>按钮< / button>

OnClick -

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

代码没有得到这个事件事件,虽然按钮类更改为newClass。 >

谢谢

解决方案

这是因为绑定点击事件元素有另一个



尝试像下面这样的东西:

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

示例


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

解决方案

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

这篇关于动态添加类的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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