Jquery addClass - 新类的函数

时间:2015-03-15 03:59:25

标签: javascript jquery click addclass

我的js文件中存在问题。 这是我的Js Code。

<script type="text/javascript">
 $(document).ready(function()
   {

    $(".abc").click(function()
    {
     $(this).addClass('testingClass');
    });
    $(".testingClass").click(function()
    {
      alert("hiiiiiiiiiiiiiiiiii")

    });
  });
</script>

我的HTML:

<button class="abc">Demo</button>

当我在浏览器中加载此页面时,addClass函数成功执行并添加名为“testingClass”的新类。

但是当尝试再次单击该按钮(meens:class =“testingClass”)时,警报功能无效。错误是什么。

JS是否不支持频繁执行元素? 有人请帮帮我。

步骤..

  1. One Button的类名为abc
  2. 点击它时,ajax函数会将当前时间存储在数据库中。(ajax函数不在堆栈代码中)。
  3. 成功执行ajax响应后,按钮类更改为testingClass。
  4. 现在按钮的类名是testingClass
  5. 过了一段时间再次单击Button(类名为:testingClass),我想用当前的click时间调用ajax函数并将值存储在数据库中。
  6. 然后Button类名称将更改为old(abc)。

2 个答案:

答案 0 :(得分:1)

您需要event delegation获取动态添加元素

$(document).on("click",".testingClass",function()
 {
   alert("hiiiiiiiiiiiiiiiiii")

 });

Event delegation

答案 1 :(得分:1)

更新

对于已更改的问题,您正在寻找类似的内容。 这是demo

$('body').on('click', '.abc', function () {
    // event attached to .abc
    // updateTime is a method that takes context (this), current timestamp and a function
    // we need to send the context so that we have access to the current 
       element inside the below function which is executed outside the scope
    updateTime.call(this, new Date().getTime(), function (data) {
        $(this).addClass('testingClass').removeClass('abc');
        $('#log').append('Time: ' + data + 'from abc <br/>');
    });
}).on('click', '.testingClass', function () {
    // event attached to .abc
    updateTime.call(this, new Date().getTime(), function (data) {
        $(this).addClass('abc').removeClass('testingClass');
        $('#log').append('Time: ' + data + ' from testingclass <br/>');
    });
});

function updateTime(currentTime, successCallback) {
    $.ajax({
        context: this, // the context sent from the above methods is used here
        url: '/echo/html/',
        data: {
            html: currentTime
        },
        method: 'post',
        success: successCallback
    });
}

使用.one()可以帮助您在多次点击后仅附加一次事件。

  

每个事件类型的每个元素最多执行一次此处理程序。

我认为这就是你要找的东西。在添加类之后添加处理程序。

$(".abc").click(function(){
    $(this).addClass('testingClass');
    $(".testingClass").one('click', function() {
      alert("hiiiiiiiiiiiiiiiiii");
    });
  });

$(document).ready(function() {

  $(".abc").click(function() {
    $(this).addClass('testingClass');
    $(".testingClass").one('click', function() {
      alert("hiiiiiiiiiiiiiiiiii");
    });
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="abc">Demo</button>