Adding onclick handler using jQuery attr method does not work in IE

The following code works fine in Firefox. In IE (8.0), the "2" button does not work.

$('<button type="button" onclick="alert(1)">1</button>').appendTo($('body'));
$('<button type="button" >2</button>').attr('onclick','alert(2)').appendTo($('body'));

Question: what am I doing wrong?

+3
source share
1 answer

You must attach clickhandlers .click(), for example:

$('<button type="button">2</button>').click(function() { alert(2); }).appendTo($('body'));

This is a shortcut for .bind('click', func), although you can associate any event with several such shortcuts available .

+3
source

Source: https://habr.com/ru/post/1759975/


All Articles