在不存在的html元素上触发jQuery.click()事件

jQuery .click() trigger event on non-existent html element

本文关键字:click jQuery 事件 不存在 html 元素      更新时间:2023-09-26

我有一个ID为"open"的HTML按钮。我在ID选择的HTML按钮上添加了一个jQuery .click()绑定。在.click()绑定中,我将ID"打开"更改为"关闭"。然而,即使ID已更改为"关闭",随后单击"打开"按钮仍会触发。代码如下:

index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <button id="open">Open</button>
    <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
</body>
</html>

index.js

$('#open').click(function() {
    console.log("clicked");
    $(this).attr('id', 'close');
});

https://jsfiddle.net/iHexBot/28tj1ywg/

我期待/希望看到控制台日志只被"点击"了一次。然而,即使HTML元素ID不再"打开",它也会在每次单击按钮时记录"已单击"。有人能向我解释为什么会发生这种情况吗?如果可能的话,如何解决?

您可以将事件绑定到文档,而不是像这样的元素

$(document).on('click', '#open', function() {
    console.log('this will only be displayed as long as id is "open"');
});

如果你只想触发一次,我会试试这个:

$('#open').one("click", function() {
    console.log("clicked");
    $(this).attr('id', 'close');
});

但如果你正在创建一个"切换"按钮,我不会这样做。正如这里的另一个答案所暗示的那样,我会创建一个活动,根据它应该是开幕还是闭幕而采取不同的行动。

改为使用此脚本:

$('#open').bind('click', function() {
    console.log("clicked");
    $(this).attr('id', 'close').unbind('click');
});

以下是在openclose 之间切换的代码

<button class="toggleButton" data-option="open">Open</button>
$(document).on('click','.toggleButton',function() {
 if($(this).attr('data-option') == 'open') {
  console.log('open');
  // do something if "open" clicked;
  $(this).text('Close');
  $(this).attr('data-option','close');
 }else{
  console.log('close');
  // do something if "close" clicked;
  $(this).text('Open');
  $(this).attr('data-option','open');    
 }
});

jsfiddle-https://jsfiddle.net/ygf1327m/

为此,您"应该"使用ONE(),而不是解除绑定。为了证明这一点,我编辑了你的原始JSFIDDLE。

   jQuery(document).ready(function ($) 
    {  
    //the element to evaluate
     var current_id= $("button#open");
     alert("The ID of the button is: " + current_id.attr("id") );
     current_id.one("click", function () {  
     //now once we click the button we have
     current_id.attr('id', 'close');
     alert("Now the ID is: " + current_id.attr('id') + "  so we are changing it''s text too...  "  );
     //reflect the change
     current_id.text("Close");     
     });
    });

JSFIDDLE:
https://jsfiddle.net/28tj1ywg/4/

jQuery将在浏览器加载时绑定一个.click()事件,而不是在每次单击后重新绑定。

你会想要.unbind()这个事件来解决你的问题。

$('#open').click(function() {
  console.log("clicked");
  $(this).attr('id', 'close');
  $(this).unbind();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="open">Open</button>

  • .unbind()|jQuery

原因是在执行事件处理程序时,其上下文(即"this"对象)与定义上下文不同。另请参阅如何将this上下文传递到事件处理程序中?