2015-11-02 112 views
2

我有一个ID为“open”的HTML按钮。我已经添加了一个jQuery .click()绑定到由ID选择的HTML按钮。在.click()绑定中,我将“打开”的ID更改为“关闭”。但是,即使ID已更改为“关闭”,后续点击“打开”按钮仍会触发。代码如下:jQuery .click()在不存在的html元素上触发事件

的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不再“打开”,每次单击按钮时都会记录“单击”。有人可以向我解释为什么会发生这种情况,如果可能的话,如何解决这个问题?

+3

您必须在事件再次绑定,或使用代表团的功能就像() – FLX

+0

然后你要绑定到$(“#闭”),并做了关闭功能?还是你只是这样做,以便事件只触发一次? – Dhunt

回答

0

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>

2

如果你只是想触发一次我想尝试这样的:

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

,但如果你正在创建一个 '切换'按钮我不会这样做。我会创建一个事件,根据是否应该打开或关闭而采取不同的行动,正如其他答案所暗示的。

1

使用此脚本:

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

下面是切换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/

2

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

1

为此目的,您“应该”使用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/

相关问题