简体   繁体   中英

JavaScript (jquery) append issue with IE9

im using jquery to add a quickmenue to my website. my source code is like this :

var span = $('body').append('<span id="quickmenu">');
       $('#quickmenu').css('position','fixed')
              .css('background-color','white')
              .css('border','4px solid black')
              .css('border-left','0px solid black')
              .css('top','15px')
              .css('left','0px')
              .css('font-family','Calibri')
              .css('font-size','14px')
              .css('line-height','0px')
              .css('color','#777777')
              .css('text-align','center');

My problem on that is, everything works really fine in FF and Chrome, but IE9 isn't showing anything to me.

So i tried some alerts() after accessing the above code...:

alert('I run'); // I run
alert(span); // [object Object]
alert($("#quickmenu")); // [object Object] 
alert(span == $("#quickmenu")); // false

So i seems to be created , but not shown?!

I really have no idea what went wrong there,.... Console shows no errors in FF and IE9

Any ideas ?! :-/

I believe the code is running too early. You need to wrap your code in the document ready function:

jQuery(document).ready(function() {

//your code goes here

});

I would in fact change your function to something like below:

 jQuery(document).ready(function(e) {   
    var span = $('<span id="quickmenu" >')
        .css({
            'position':'fixed',
             'background-color':'white',
             'border':'4px solid black',
             'border-left':'0px solid black',
             'top':'15px',
             'left':'0px',
             'font-family':'Calibri',
             'font-size':'14px',
             'line-height':'0px',
             'color':'#777777',
             'text-align':'center'
        })
        .appendTo($("body"));
});

As Smoki pointed out in the comments.

Switching from: $("#target").append(my_dom_element);

to: my_dom_element.appendTo("#target");

Seems to solve the issue.

I was using a large but unscripted element that I was importing from an external file and turning into an element in advance. Then the append would fail. Switching to using the .appendTo() method worked. So I would hazard a guess that the IE code for .append() gets confused when asked to append complex elements. Though it could just as easily be what it was appending it to that confused it.

(jQuery 1.8.2)

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