jQuery On Click 功能只能运行一次

tol*_*ube 2 wordpress jquery onclick

我知道 stackoverflow 中有很多类似的问题,但似乎没有一个对我有用。我认为存在逻辑错误,导致我的 onClick 事件无法多次工作。另外,我想传递 data-id 属性以通过 id 定位正确的容器。它确实有效,但只能一次。我在 WordPress 页面中使用它。这是我的代码:

jQuery(document).ready(function($){

    $('.change-aktiviert-btn').on('click', function(){
        var id = $(this).data("id");
        if($('#project-listing-container-'+id).hasClass("grey-bg")) {
            $('#project-listing-container-'+id).removeClass("grey-bg");
        } else {
            $('#project-listing-container-'+id).addClass("grey-bg");
        }
    })

})
Run Code Online (Sandbox Code Playgroud)

相关的 HTML 是:

<div id="project-listing-container-398" class="project-listing-container "></div>
    <button class="change-aktiviert-btn" data-id="398" onclick="changeStatus('Ja', 1, 398);" type="button" name="qr-link">
                    <div class="project-action-switch">
                        <i class="fas fa-eye"></i>
                    </div>
        </button>
Run Code Online (Sandbox Code Playgroud)

我该如何修复它?感谢您的帮助。

Moo*_*oob 7

似乎对我来说可以工作多次。下面演示。你的例子中肯定还缺少其他东西。尽管在您的问题中并不明显,但我怀疑您正在替换.change-aktiviert-btn代码中其他位置的元素,从而丢失分配给它的事件侦听器。您可以使用事件委托来避免这种情况。

$(function(){

    $('body').on('click', '.change-aktiviert-btn', function(){//delegated
        console.log("click");
        var id = $(this).data("id");
        $('#project-listing-container-'+id).toggleClass("grey-bg");
    })

});

function changeStatus(a,b,c){
  //dunno what this is
  console.log(a,b,c);
};
Run Code Online (Sandbox Code Playgroud)
.grey-bg {
background:grey;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="project-listing-container-398" class="project-listing-container ">
I'm the listing container.
</div>
    <button class="change-aktiviert-btn" data-id="398" onclick="changeStatus('Ja', 1, 398);" type="button" name="qr-link">
                    <div class="project-action-switch">
                        <i class="fas fa-eye"></i>
                    </div>
        </button>
Run Code Online (Sandbox Code Playgroud)

  • 听起来您正在尝试将事件侦听器添加到不存在的元素。使用事件委托(https://learn.jquery.com/events/event-delegation/)来侦听可能尚不存在或稍后将被替换的元素上的事件。我更新了我的演示以反映这一变化。 (2认同)