jQuery setting onclick attribute working only on FireFox?

霸气de小男生 提交于 2019-12-25 06:46:02

问题


I'm trying to set the "onclick" attribute of a link generated with jQuery.

While other attributes work without problem (eg. href, but also other custom attrs), setting "onclick" seems to only work in FireFox. On other browsers the attribute just gets ignored.

Any hint? Is this behaviour correct? And why?

<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
  jQuery(function(){
    var obj = $('<a/>');
    obj.html('click me');
    obj.attr({'href':'#test', 'onclick':'alert("o hai"); return false;'});
    $('body').append(obj);
  });
</script>
</head><body /></html>

EDIT: I know about the .click() jQuery method; but that's not the point, I just want to set the attribute and can't figure out why it doesn't work like any other attr does.


回答1:


Is this behaviour correct?

In as much as attr('onsomeevent', ...) has never been the way to add event listeners, has never been supported, and only works on Firefox due to coincidence, yes.

And why?

Because IE before version 8 can't directly get/set HTML attributes. Calling setAttribute() only sets a DOM property of the same name. And the onclick property isn't a string property so you can't write a string to it. It only accepts a function value.

jQuery's attr() muddies the issue by being called attr but actually writing to DOM properties and not HTML attributes... but using HTML attribute names (like eg. class) rather than DOM property names (like className).

(Except when it doesn't, because for some cases it tries to hide the difference by using attributes. Except that still doesn't work all the time in IE for the reason above. This is not one of jQuery's proudest moments.)

Anyhow, in general having JavaScript in a string is a code smell. The best way forward for jQuery and modern JavaScript in general is to use function objects (possibly inline function() { ... } expressions) instead.




回答2:


try it jQuery way....

<script type="text/javascript">
  jQuery(function(){
    var obj = $('<a/>');
    obj.html('click me')
       .attr('href','#test')
       .click(function() {
            alert("o hai");
            return false;
        })
    $('body').append(obj);
  });
</script>

edit: try changing onclick to onClick, note the capital "C"

jQuery(function(){
    var obj = $('<a/>');
    obj.html('click me');
    obj.attr({'href':'#test', 'onClick':'alert("o hai"); return false;'});
    $('body').append(obj);
  });


来源:https://stackoverflow.com/questions/2825533/jquery-setting-onclick-attribute-working-only-on-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!