jQuery On Click函数仅可使用一次

时间:2019-03-01 12:47:50

标签: jquery wordpress 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");
        }
    })

})

相关的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>

我该如何解决? 感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

似乎可以为我工作多次。下面的演示。您的示例中肯定还缺少其他内容。尽管在您的问题中看不到它,但我怀疑您是在代码中的其他地方替换了.change-aktiviert-btn元素,因此失去了分配给它的事件侦听器。您可以使用event delegation来避免这种情况。

$(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);
};
.grey-bg {
background:grey;
}
<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>

答案 1 :(得分:0)

我认为您身边可能缺少有关id的信息。

请在此处https://jsfiddle.net/0suxapvf/中查看包含您的代码的工作示例,其中为点击添加了属性data-id

HTML

<a href="javascript:void(0)" class="change-aktiviert-btn" data-id="1">Click here</a>

<div id="project-listing-container-1">
Project stuff here
</div>

jQuery

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

    $('.change-aktiviert-btn').on('click', function(){
        var id = $(this).attr("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");
        }
    })

})