[英]How can I replace the onclick action (with regex) using javascript / jQuery?
How can I use jQuery to replace part of the onclick
property / attribute? 如何使用jQuery替换部分onclick
属性/属性? In the example below I would like to replace delete_image
with do_delete_image
: 在下面的示例中,我想用do_delete_image
替换delete_image
:
<a href="#" onclick="delete_image(1234)" >Delete Image</a>
jQuery('a').each(function(){
var action = $(this).prop('onclick').replace('delete_image','do_delete_image');
$(this).prop('onclick',action);
});
Google chrome is throwing this error: Google Chrome正在抛出此错误:
TypeError: Object function onclick(event) { delete_image(1234);return false; TypeError:对象函数onclick(event){delete_image(1234); return false; } has no method 'replace' 没有方法'替换'
How can I make this work? 我怎样才能做到这一点? ps: This is a bookmarklet set to work with someone else's code. ps:这是一个设置为与其他人的代码一起使用的书签。
onclick
is a property representing the function that handles the click
event. onclick
是一个表示处理click
事件的函数的属性。 To get and set the actual content, use attr
instead of prop
. 要获取和设置实际内容,请使用attr
而不是prop
。
Alternatively, consider replacing delete_image
with do_delete_image
, for example: 或者,考虑用do_delete_image
替换delete_image
,例如:
window.delete_image = window.do_delete_image;
You can combine this with closures if you need to wrap the original function. 如果需要包装原始函数,可以将其与闭包结合使用。
使用$(this).unbind()清除该元素上的处理程序,然后添加新元素
As of jQuery 1.7, this should work... 从jQuery 1.7开始,这应该有效......
jQuery('a').each(function(){
$(this).off('click')
.on('click', do_delete_image);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.