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

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

问题描述

我有一个表单,其中按钮的类是动态变化的,具体取决于请求的来源.我正在尝试捕获 onclick 事件,但它不包含动态添加的类.我确保该类被添加到按钮中.我哪里出错了.

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.

片段 --

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

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

点击--

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

虽然按钮类已更改为 newClass,但代码未到达此事件事件.

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

谢谢

推荐答案

那是因为当你绑定点击事件时,元素有另一个类.

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

试试这样的:

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

示例

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

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