Bug Tracker

Opened 14 years ago

Closed 13 years ago

Last modified 11 years ago

#4281 closed bug (wontfix)

Can't overwrite onclick attr

Reported by: gelform Owned by:
Priority: minor Milestone: 1.4
Component: attributes Version: 1.3.2
Keywords: onclick attribute attr Cc: corey@…
Blocked by: Blocking:


On an element, I can add an attribute of onclick: $('#myLink').attr('onclick', "alert('test');")

But then I cannot rewrite/reset it: $('#myLink').attr('onclick', "alert('test2');") doesn't work

$('#myLink').attr('onclick', "") doesn't work

and if I remove it, I cannot then readd it: $('#myLink').removeAttr('onclick') works $('#myLink').attr('onclick', "alert('test3');") doesn't work

Change History (3)

comment:1 Changed 14 years ago by dmethvin

There is some magic that the browsers do to convert the string onclick attribute into an onclick function property. When you set the onclick *attribute* to a string it also sets the onclick *property* to a function object that it creates from the string you gave it.

When you set the onclick attribute the second time, jQuery sees the existing onclick property and believes that it should set the property in preference to the attribute. In doing that it changes the function to a string.

However, you can still change the onclick handler by assigning a function directly to the property, rather than the attribute:

  $('#myLink')[0].onclick = function(){ alert("test2"); };

You can also clear the onclick the same way by assigning a null.

Is there a reason why you're avoiding the jQuery event support?

comment:2 Changed 13 years ago by dmethvin

Component: supportattributes
Summary: Can't overwrite onclick attr or re-add it after removingCan't overwrite onclick attr

comment:3 Changed 13 years ago by snover

Resolution: wontfix
Status: newclosed

I don’t feel that jQuery should do anything to encourage bad practices like this. Feel free to reopen if there is any disagreement in that regard.

Note: See TracTickets for help on using tickets.