开发者

Onclick event doesn't work when .append()

Simple example: I have html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="portal.css" />
        <script type="text/javascript" src="/test/lib.js"></script>
        <script type="text/javascript" src="test.js"></script>
    </head>
    <body onload="init();" class="body">
        <div id="wrapper">
        </div>
    </body>
</html>

then I call

$("#wrapper").append(
        "<div onclick=\"alert('TEST')\" style=\"background-color: aqua; width: 20px; height: 20px; position: absolute\">" +
        "</div>"
    );

so appears small box, when I click it in FF or Chrome - alert box appears. But problem is: in IE8 onclick doesn't work. It works when I use .html("...").

Please, help开发者_StackOverflow me! =) Thank you!


You could use jQuery to create the new div. This would let jQuery handle the click-logic between browsers. I just tested what follows in IE8, and it works:

$("<div>")
  .css({'background-color':'aqua','width':'20px','height':'20px','position':'absolute'})
  .click(function(){ alert("TEST"); })
  .appendTo("#wrapper");

Online Demo: http://jsbin.com/ekumi/edit


It seems that IE8 can't process events declared in html tags that are empty, even though they are given non-zero measures through css.

Try adding '&nbsp;' as content. It worked for me.


This is probably a security feature, possibly related to the fact that IE cannot directly return a function through eval.

As a workaround, you could build a DOM tree using jQuery, then write $("#wrapper").empty.append(tree).


IE has a problem evaluating dynamically inserted html and their events. I think this is because inline onclick/onmouseover/etc. has to be parsed by the HTML engine on page load and they are not fully parsed when inserting elements through JS. Sometimes it works, and other times it doesn't. It's much better to insert the element first, and then wire an event to it after that:

$("#wrapper").html("<div id=\"newdiv\" style=\"background-color: aqua; width: 20px; height: 20px; position: absolute\"></div>");
$("#newdiv").click("function() { alert("TEXT"); });


First of all, I'm sorry - in question code must contain .append(...) - and this is not working in IE. I already edited question.

I solve the problem in this way:

$('<div>').append($('#item-of-interest').clone()).remove().html();

But I still don't understand why IE behaves incorrect with append method. =(

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜