简体   繁体   English

更新jquery中的div ID,以便脚本只能运行一次

[英]Update div id in jquery so script can only run once

I currently have a script that I am using in my website. 我目前在网站上使用的脚本。 The goal of the script is when the user clicks the link, the javascript function will fire. 脚本的目标是当用户单击链接时,将触发javascript函数。 This function is based off of the div id. 此功能基于div id。 At the end of the function I use jquery to change said div id. 在函数的结尾,我使用jquery更改了div id。 However, when the user clicks the link again the function still fires, even though the id has changed. 但是,当用户再次单击该链接时,即使ID已更改,该功能仍会触发。 What am I doing wrong? 我究竟做错了什么? How can I get the script to only execute the first time the link is clicked? 如何获得仅在首次单击链接时执行的脚本?

$("#down").click(function(){
            var id = $("#down").attr("class");
            $.ajax({
              type: "POST",                                 
              url: "vote.php",                             
              data: "side=down&id=" + id,          
              success: function(){ alert("lul worked"); } 
            });
            $('.' + id + '#down').attr('id', 'down_stay');
        });

Now that you all have answered, what is the better choice, using "one" or using "unbind"? 既然大家都已经回答了,使用“一个”或“解除绑定”是更好的选择吗?

Don't use click , use on . 不要使用click ,使用on Or in your case, one : 或者您的情况one

$('#down').one('click', function() {
    // function only fires once and then is unbound.
});

Use $("#down").one("click", function(){}); 使用$("#down").one("click", function(){}); instead to make it fire only once. 而是使其仅发射一次。

Try using one 尝试使用one

$("#down").one('click', function(){

The DOM events are attached to the elements and not to the attributes. DOM事件附加到元素 ,而不附加到属性。

So even if you change the attributes of the element it does not mean it is a different element. 因此,即使您更改元素的属性,也并不意味着它是不同的元素。

The event will only be removed if that particular element will be removed from the DOM.. 仅当从DOM中删除该特定元素时,才会删除该事件。

Use unbind() instead. 请改用unbind()

replace 更换

$('.' + id + '#down').attr('id', 'down_stay');

with

$( this ).unbind( 'click' );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM