views:

130

answers:

4

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 me! =) Thank you!

A: 

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).

SLaks
+3  A: 

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

Jonathan Sampson
A: 

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"); });
Ilya Volodin
A: 

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. =(