繁体   English   中英

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

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

我有一个ID为“open”的HTML按钮。 我已经添加了一个jQuery .click()绑定到由ID选择的HTML按钮。 .click()绑定中,我将“open”的ID更改为“close”。 但是,即使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不再“打开”,它也会在每次单击按钮时记录“单击”。 有人可以向我解释为什么会发生这种情况,如果可能的话,如何解决这个问题?

如果您只想触发一次,我会尝试这样做:

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

但是如果你要创建一个“切换”按钮,我不会这样做。 我会根据它是应该打开还是关闭来创建一个不同的事件,正如其他答案所示。

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

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

请改用此脚本:

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

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

暂无
暂无

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

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