javascript 我们如何通过 .attr() 在 jquery 中更改 onclick 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3604906/
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
how do we change onclick function via .attr() in jquery?
提问by justjoe
i got this url
我有这个网址
<a class="remove_item' rel="4" onclick="javascript:jQuery(#blablabla)" href="javascript:;' >remove</a>
i'm using this simple find and replace
我正在使用这个简单的查找和替换
item.find('a.remove_class').attr({
title:'hello',
click:'hello();'
} );
but it seem it's not working. i still not able to replace javascript:jQuery(#blablabla) with another function.
但它似乎不起作用。我仍然无法用另一个函数替换 javascript:jQuery(#blablabla)。
回答by Sorantis
To set onClick you should use something like this $("a").attr("onclick", js);
要设置 onClick 你应该使用这样的东西 $("a").attr("onclick", js);
where js is a string containing your javascript code.
其中 js 是包含您的 javascript 代码的字符串。
回答by Hari Pachuveetil
Try attaching the event handler using the below code snippet in your page body:
尝试使用页面正文中的以下代码段附加事件处理程序:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('.remove_item').click(hello);
});
</script>
回答by Tim Down
jQuery has no built-in way to assign event handlers in that way. Use the DOM0 method to set the onclickhandler instead:
jQuery 没有以这种方式分配事件处理程序的内置方法。使用 DOM0 方法来设置onclick处理程序:
item.find('a.remove_class').each(function() {
this.onclick = function() {
alert("Clicked!");
};
});
Also, don't put javascript:in you event handler attributes. It's incorrect and only works by coincidence.
另外,不要放入javascript:事件处理程序属性。这是不正确的,只是巧合。
回答by Randall Kwiatkowski
Why not just do this.
为什么不这样做。
<script type="text/javascript">
$(document).ready(function() {
$("a.remove_item").click(function() {
alert("You have clicked my <a>!!");
//do other stuff
});
});
</script>
回答by BrunoLM
The attr doesn't recognises the onclick attribute, get the html element (.get(0)) and use "raw" functions to extract the onclick attribute.
attr 无法识别 onclick 属性,获取 html 元素 ( .get(0)) 并使用“原始”函数来提取 onclick 属性。
On Firefoxthe following works:
在Firefox 上执行以下操作:
$("element").get(0).getAttribute("onclick")
You can remove by using
您可以使用删除
$("element").get(0).removeAttribute("onclick")
or setting a empty string
或设置一个空字符串
$("element").get(0).setAttribute("onclick", "")

