我想更改 anchor 上 onclick
属性的值。我想将它设置为一个包含 JavaScript 的新字符串。 (该字符串由服务器提供给客户端 JavaScript 代码,它可以包含您可以放入 HTML 中的 onclick
属性中的任何内容。)以下是我尝试过的一些方法:
- 使用 jQuery
attr("onclick", js)
不适用于 Firefox 和 IE6/7。 - 使用
setAttribute("onclick", js)
适用于 Firefox 和 IE8,但不适用于 IE6/7。 - 使用
onclick = function() { return eval(js);
不起作用,因为您不允许使用return
是传递给eval()
的代码。
有人建议将 onclick 属性设置为以使其适用于 Firefox 和 IE 6/7/8 吗?另请参阅下面我用来测试它的代码。
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var js = "alert('B'); return false;";
// Set with JQuery: doesn't work
$("a").attr("onclick", js);
// Set with setAttribute(): at least works with Firefox
//document.getElementById("anchor").setAttribute("onclick", js);
});
</script>
</head>
<body>
<a href="http://www.google.com/" id="anchor" onclick="alert('A'); return false;">Click</a>
</body>
</html>
最佳答案
你不应该使用 onClick
如果您使用的是 jQuery,则更多。 jQuery 提供了自己的附加和绑定(bind)事件的方法。参见 .click()
$(document).ready(function(){
var js = "alert('B:' + this.id); return false;";
// create a function from the "js" string
var newclick = new Function(js);
// clears onclick then sets click using jQuery
$("#anchor").attr('onclick', '').click(newclick);
});
那应该取消 onClick
函数 - 并保留您的“来自字符串的 javascript”。
最好的办法是删除 onclick=""
来自 <a>
HTML 代码中的元素并切换到使用 Unobtrusive将事件绑定(bind)到点击的方法。
你还说:
Using
onclick = function() { return eval(js); }
doesn't work because you are not allowed to use return in code passed to eval().
不 - 它不会,但是 onclick = eval("(function(){"+js+"})");
会将“js”变量包装在函数外壳中。 onclick = new Function(js);
也可以工作,并且阅读起来更清晰。 (注意大写 F)——见 documentation on Function()
constructors
关于JavaScript:使用或不使用 jQuery 更改 onclick 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/826628/