简体   繁体   中英

Dynamically creating div with JQuery 2.0.2 or 2.0.3 not working

I would like to know the difference between 1.9.1 and 2.0.2 in regards to the jsFiddle attached.

HTML:

<div id='M1' style='width:100%; border:1px solid red;'>Main Container</div>

JS:

// first method
$("#M1").append("<div>method 1</div>");

// second method
jQuery('<div/>', {
    title: 'Method 2',
    rel: 'external',
    style: 'width:90%; border: 1px solid green;',
    text: 'Method 2'
}).appendTo('#M1');

// third method
$('<div/>', {
    'id':'myDiv',
    'text':'Method 3',
}).on('click', function(){
    alert(this.id); // myDiv
}).appendTo('#M1');

http://jsfiddle.net/Dzbza/5/

Why does it work with jQuery 1.9.1 but not in 2.0.2.

What would be the equivalent code that would work in 2.0.2 or 2.0.3

If you run the example using 1.9.1 it works fine, if you change id to 2.0.2 it doesn't

Thank you

This seems to be specific to jsFiddle, possibly the frame environment in which it works. I can replicate your result with IE10 using jsFiddle , but if I create a page of my own using jQuery v2.0.2 and that code, it works. Similarly, the same page on JSBin works as well: Live Copy | Source

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Scratchpad</title>
<script src="//code.jquery.com/jquery-2.0.2.js"></script>
</head>
<body>
<div id='M1' style="width:100%; border:1px solid red;">Main Container</div>
<script>
// first method
$("#M1").append("<div>method 1</div>");

// second method
jQuery('<div/>', {
    title: 'Method 2',
    rel: 'external',
    style: 'width:90%; border: 1px solid green;',
    text: 'Method 2'
}).appendTo('#M1');

// third method
$('<div/>', {
    'id':'myDiv',
    'text':'Method 3',
}).on('click', function(){
    alert(this.id); // myDiv
}).appendTo('#M1');
</script>
</body>
</html>

So fundamentally, there is no problem, because it does work...except in that environment.

When the fiddle fails, I get two errors in the Dev Tools in IE10:

SCRIPT5: Access is denied.
jquery-2.0.2.js, line 1378 character 2
SCRIPT5009: '$' is undefined 
show, line 20 character 1

Here's jQuery-2.0.2.js line 1378 in context:

1375|  // Support: IE>8
1376|  // If iframe document is assigned to "document" variable and if iframe has been reloaded,
1377|  // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
1378|  if ( parent && parent.frameElement ) {
1379|    parent.attachEvent( "onbeforeunload", function() {
1380|      setDocument();
1381|    });
1382|  }

So again, this suggests something specific to the jsFiddle environment. It may be worth checking the jQuery issue tracker to see if it's a known issue and, if not, reporting it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM