jquery onclick 点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4052886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery onclick click event
提问by user367134
I have div which has an onlcick event. Now when i click the div i want to change its onlick function with .click attribute of jquery. I am able to change it dynamically, but when i apply it the new event also gets fired. Is there any work around so that the new is not fired but just applied to the div with new function? Here is what i am trying to do
我有一个 div,它有一个 onlcick 事件。现在,当我单击 div 时,我想使用 jquery 的 .click 属性更改其 onlick 功能。我可以动态更改它,但是当我应用它时,新事件也会被触发。是否有任何解决方法可以使 new 不会被触发,而只是应用到具有 new 功能的 div 上?这是我想要做的
i have a div
我有一个div
<script type="text/javascript">
function testMe(data)
{
alert(data);
$('#testMe').unbind('click');
$('#testMe').click(function(){ testMe('2'); });
}
</script>
<div id='testMe' onclick='testMe(1)' >click on me, I will disappear.</div>
when I execute theabove code i still get value 1 om alert box THANKS EveryOne
当我执行上述代码时,我仍然得到值 1 om 警报框谢谢大家
Also i tried the below code but it is not working for me
我也尝试了下面的代码,但它对我不起作用
function testMe(data)
{
alert(data);
$('#testMe').unbind('click');
$('#testMe').click( testMe(2) );
}
Though the code is updating the onlick event from 'testMe(1)' to 'testMe(2)' but it continuously alerts value 2. The work around this problem is traditional JS script code as:
尽管代码正在将 onlick 事件从“testMe(1)”更新为“testMe(2)”,但它不断提醒值 2。解决此问题的方法是传统的 JS 脚本代码:
document.getElementById('testMe').onclick = testMe(2) ;
And its working without alerts.
它的工作没有警报。
回答by DoXicK
回答by castis
maybe try this.
也许试试这个。
$('div').click(function(){
$(this).unbind('click');
$(this).click(function(){
// new click function here
});
});
回答by Pete Amundson
Try using the bind event http://api.jquery.com/bind/
尝试使用绑定事件http://api.jquery.com/bind/
If you want to remove the previous event use the unbind event: Best way to remove an event handler in jQuery?
如果要删除前一个事件,请使用 unbind 事件: Best way to remove an event handler in jQuery?
回答by Mark Baijens
unbind old functionality first. Than bind the new event to it should do the trick.
首先取消绑定旧功能。比将新事件绑定到它应该可以解决问题。
Do you mean the the event is also fired when you bind it to the element?
您的意思是将事件绑定到元素时也会触发事件吗?