JavaScript:使用或不使用jQuery更改onclick的值

ave*_*net 48 javascript jquery attributes onclick

我想onclick在锚点上更改属性的值.我想将其设置为包含JavaScript的新字符串.(该字符串由服务器提供给客户端JavaScript代码,它可以包含您可以onclick在HTML 中的属性中放置的任何内容.)以下是我尝试过的一些内容:

  • 使用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>
Run Code Online (Sandbox Code Playgroud)

gna*_*arf 74

onClick如果您使用的是jQuery,则不应再使用它.jQuery提供了自己的附加和绑定事件的方法.看到.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);
});
Run Code Online (Sandbox Code Playgroud)

这应该取消该onClick功能 - 并保持你的"javascript从一个字符串".

最好的办法是onclick=""<a>HTML代码中删除元素,然后切换到使用Unobtrusive方法绑定事件以进行单击.

你还说:

使用onclick = function() { return eval(js); }不起作用,因为不允许在传递给eval()的代码中使用return.

不 - 它不会,但onclick = eval("(function(){"+js+"})");会将'js'变量包装在函数机箱中. onclick = new Function(js);同样有效,读起来也更清洁.(注意大写字母F) - 请参阅构造函数的文档Function()

  • attr('onclick','')不起作用,你需要使用removeAttr('onclick') (5认同)
  • 请注意这一点:jQuery unbind()vs removeAttr()请参阅http://www.novogeek.com/post/2009/05/18/Beware-e28093-jQuery-unbind()-vs-removeAttr().aspx (2认同)