Bug Tracker

Ticket #4281 (closed bug: wontfix)

Opened 6 years ago

Last modified 3 years ago

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@…
Blocking: Blocked by:

Description

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

comment:1 Changed 6 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 4 years ago by dmethvin

  • Component changed from support to attributes
  • Summary changed from Can't overwrite onclick attr or re-add it after removing to Can't overwrite onclick attr

comment:3 Changed 4 years ago by snover

  • Status changed from new to closed
  • Resolution set to wontfix

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.