简体   繁体   中英

jQuery(1.6.4) using append() to add anchor does not work in IE

I am really having trouble using the append() function with IE.

What I am trying to do is the following:

  1. Append anchor tag to the body element
  2. Bind a modalwindow plugin to the anchor tag
  3. Fire the click event on the anchor tag to open the modal window
  4. Remove the anchor tag afterwards

     if($('a#' + id).length == 0){ $('body').append('<a id=\\"' + id + '\\" href=\\"' + gJsAppBasePath + url + '\\" class=\\"iframe\\" title=\\"' + title + '\\"><\\a>'); $('a#' + id).fancybox({ 'hideOnContentClick': false, width: width, height: height }); } $('a#' + id).click(); $('a#' + id).remove(); 

As expected it works fine in Chrome, FF and Opera, but it doesn't in IE.

What I have already tried to solve this issue:

  1. Mess around with the apostrophs and quotations
  2. Simplify the anchor tag to minimum <a href="../index.html>&nbsp;</a>
  3. Try the same with another tag <h2>BlaBla</h2>

The anchor tag never is initialized to a proper jQuery object. The h2 tag is, but it won't be shown on the page.

I have found a workaround to hardcode the anchor tag and modify the attributes, but this is not really what I want. Any ideas are very much appreciated.

Thank you in advance, Sebastian

I would expect your code to look more like this:

var anchor = $('#' + id);
if(anchor.length === 0){
    anchor = $('<a id=\"' + id + '\" href=\"' + gJsAppBasePath + url + '\" class=\"iframe\" title=\"' + title + '\"><\a>'); 
    $('body').append( anchor );
    anchor.fancybox({
        'hideOnContentClick': false,
        width: width,
        height: height
    });
}
anchor.click().remove();

Using selectors like element#id are a lot slower than just doing #id . Plus in certain versions of IE, it seems to have issues.

Also $('a#' + id) is expensive and you do it multiple times. There is no need to do it time and time again. You just need to do it once and reuse it wither by variables or chaining.

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