大家好,我有一个有趣的问题:
是否可以复制像这样元素的onclick事件:
$('#ElementId').attr('OldOnClick',$('#ElementId').attr('OnClick'));
请指导我如何实现这个功能。
我正在尝试在某个阶段禁用表单上所有元素的点击事件,而在另一个阶段,我需要恢复它们,因此我正在尝试使用其他属性名称保存它们的
onclick
。大家好,我有一个有趣的问题:
是否可以复制像这样元素的onclick事件:
$('#ElementId').attr('OldOnClick',$('#ElementId').attr('OnClick'));
onclick
。是的,您可以访问处理程序函数。在jquery中执行此操作的方法如下:
$('#specialbutton').click(function(){ console.log("peaches");};
var handlerFunction = $('#specialbutton').data("events").click[0].handler;
$('#specialbutton').click(); // "peaches"
handlerFunction(); // "peaches"
然后,您可以将它分配给另一个元素,如下所示:
$('#otherelement').click(handlerFunction);
$('#otherelement').click(); // "peaches"
.data("events").click[0].handler
获取到了你的点击处理程序的句柄,你就可以将它复制到任何你想要的地方。例如:你可以这样做$('#specialbutton').data('copied', handlerFunction);
。 - techfoobar (function($){
$.fn.copyEventTo = function(eventType, destination, clearCurrent) {
var events = [];
this.each(function(){
var allEvents = jQuery._data(this, "events");
if (typeof allEvents === "object") {
var thoseEvents = allEvents[eventType];
if (typeof thoseEvents === "object") {
for (var i = 0; i<thoseEvents.length; i++){
events.push(allEvents[eventType][i].handler);
}
}
}
});
if (typeof destination === "string") {
destination = $(destination);
} else if (typeof destination === "object") {
if (typeof destination.tagName === "string") {
destination = $(destination);
}
}
if (clearCurrent === true) destination.off(eventType);
destination.each(function(){
for(var i = 0; i<events.length; i++) {
destination.bind(eventType, events[i]);
}
});
return this;
}
})(jQuery);
这里还有另外一种方法:
//sw Get Element
var button = document.getElementById("mybutton");
//sw Get Click Function
var clickFunction = jQuery._data(button, "events").click[0].handler;
//sw Test Click Function
clickFunction();
//sw Copy ClickFunction to another Element
$('#anotherButton').click(clickFunction);
注意:之前的代码适用于以下情况:
$("#mybutton").click(function() {
//sw TODO HERE
});
显然,你不应该再这样做了,
但是你仍然可以这样做(感谢this answer):
var handlerFunction = jQuery._data( $('#ElementId').get(0), "events" ).click[0].handler;
然后,就像ChuckE的回答中所述:
$('#otherelement').click(handlerFunction);
$('#otherelement').click(); // "peaches"
不要告诉任何人...
听起来你可能漏掉下面的第二行了。在进行复制操作时,你需要进行移动操作。
$('#ElementId').attr('oldonclick', $('#ElementId').attr('onclick') )
.removeAttr('onclick');
以下代码将删除元素数据中存储的 "onclick" 并允许您稍后从数据中使用它。 以下是使用 A
标签的示例:
演示 http://jsfiddle.net/u4eVW/1/
/* remove "onclick" and store */
$('a').each(function() {
var onclick = $(this).attr('onclick')
$(this).data('oldClick', onclick)
$(this).removeAttr('onclick')
})
/* initialize handlers from data */
$('a').click(function() {
eval($(this).data('oldClick'))
})
<a href="#" onclick="alert('foo')"> Link 1</a>
var onclick=$(selector).attr('onclick').replace('foo', 'bar')
onclick
,这就是它应该做的。如果您删除 onclick,则不应触发,因此您没有清楚地表达您要寻找的内容。对于您的用例,听起来最好做一些类似于附加到$form.on("click"...)
然后在处理程序中进行检查并有条件地执行event.preventDefault();
。但是,这可能会因浏览器中的内联 js 而出现问题。 - Matt Whipple