[英]html + jquery ( Bind onclick event for execute action before onclick )
I have a question about "event click" and "order of execution". 我对“事件点击”和“执行顺序”有疑问。
I make a example here ( The HTML is generated by a external javascript ) : 我在这里举个例子(HTML是由外部javascript生成的):
HTML : HTML :
<a href="#" id="comments-replybutton" onclick="alert('Action');return false;">Comment</a>
JavaScript: JavaScript:
$(document).ready(function(){
$('#comments-replybutton').click(function(){
alert('2 attach event');
});
});
I want that when do click in "Comment" first execute the action of jquery (bind event). 我希望在单击“注释”时首先执行jquery的操作(绑定事件)。
Is this possible? 这可能吗?
$(document).ready(function(ev){
$('#comments-replybutton').click(function(ev){
alert('2 attach event');
ev.stopPropagation();
});
});
You mean, like this? 你的意思是这样吗?
Edit after comment 评论后编辑
You can also name your function to unbind: 您还可以命名函数以解除绑定:
var myEventHandler = function myFunction(ev){
$(this).unbind(myFunction);
alert('attach event 2');
ev.stopPropagation();
}
$('#comments-replybutton').bind('click', myEventHandler);
// $(something).click(fn) is just a shorthand to $(something).bind('click', fn);
Edit 2 编辑2
I guess you can kill off the original event easily, just by saying document.getElementById('comments-replybutton').onclick = "" or something similar. 我想您只需说一下document.getElementById('comments-replybutton')。onclick =“”或类似的东西,就可以轻松杀死原始事件。 You can re-attach it by copying before: 您可以通过复制以下内容来重新附加它:
var original_event_handler = $('#comments-replybutton')[0].onclick;
$('#comments-replybutton')[0].onclick = "";
$('#comments-replybutton').click(original_event_handler);
A bit dirty, but I'm too lazy to look it up :S preventDefault won't help you here, though. 有点脏,但是我懒得查找它:S preventDefault在这里对您没有帮助。
try this: 尝试这个:
$(document).ready(function(){
$('#comments-replybutton').unbind('click').click(function(){
alert('2 attach event');
});
});
and if you need also to execute the inline statement at the end, you will need something like this: 并且如果您还需要在最后执行内联语句,则将需要以下内容:
$(document).ready(function(){
var initialEvent = $('#comments-replybutton')[0].onclick;
$('#comments-replybutton').click(function(){
alert('2 attach event');
}).click(initialEvent);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.