簡體   English   中英

jQuery addClass —新類的函數

[英]Jquery addClass — Function for New Class

我的js文件有問題。 這是我的Js代碼。

<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”的新類。

但是,當嘗試再次單擊該按鈕(表示:class =“ testingClass”)時,警報功能將不起作用。 有什么錯誤。

JS是否不支持元素的頻繁執行? 有人請幫助我。

腳步..

  1. 一鍵式的類名為abc
  2. 單擊它時,一個ajax函數將當前時間存儲在數據庫中。(ajax函數不在堆棧代碼中)。
  3. 成功的ajax響應后,按鈕類更改為testingClass。
  4. 現在按鈕的類名稱為testingClass
  5. 一段時間后,再次單擊Button(名為:testingClass的類),我想用當前的單擊時間調用ajax函數並將值存儲在數據庫中。
  6. 然后,Button類的名稱將更改為old(abc)。

您需要對動態添加的元素進行event delegation

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

 });

活動委托

更新

對於變化的問題,您正在尋找類似的東西。 這是一個演示

$('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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM