簡體   English   中英

在Internet Explorer中不執行jQuery Before(和其他DOM操作)

[英]jQuery Before (and other DOM manipulations) Not Executing in Internet Explorer

我一直在搜索stackoverflow,jquery和google來尋找答案,認為肯定會有一個明確的答案,說明為什么我無法通過jquery調用.before()在Internet Explorer中運行。 它似乎可以在Chrome,Firefox,Safari和Opera中正常運行。

原始問題
我們在文檔頂部有固定的面包屑和導航欄。 本文檔的其余部分包含用適當的<p></p>標記括起來的許多段落。 在每個開頭的P標簽之前,是<a name='paragraphidentifier'>paragraphidentifier</a>格式的A錨。 通常,段標識符的格式像(1)(b)(a)一樣是引文形式。

由於在此頁頂部介紹了導航欄,因此,到這些錨點之一的任何外部超鏈接都會使錨點出現在工具欄下方。 我發現在pixelflips.com上找到合理的解決方案,方法是在錨點上方添加帶有類的span標簽。

我使用jQuery完成添加建議使用以下jQuery代碼和相關CSS的span標簽:

    if(window.location.hash){
        var myHash = window.location.hash;
        var hashName =  myHash.substring(1, myHash.length);
        $("a[name=" + hashName +"]").before("<span class='anchorfix' id='" + hashName + "'></span>");
        // I have also tried .prepend and .replaceWith
    }


    .anchorfix{
    display: block;
    height: 12px; /*same height as header*/
    margin-top: -12px; /*same height as header*/
    visibility: hidden;
}

我還嘗試了以下jQuery代碼,但均未成功。

$("a").each(function(index, element) {
    var aName = $(this).attr('name');
    var aHtml = $(this).html();
    if(aName) $(this).replaceWith("<span class='anchorfix' id='" + aName + "'></span><a name='" + aHtml + "' />" + aHtml);

我有一個使用jsfiddle上的lipsum文本的演示,在這里找到。 如果您在Chrome中進行測試,則可以使用。 如果您在IE中進行測試,則永遠不會添加span標簽。

UPDATE
我已經更新了上面的代碼以反映.before()而不是.prepend()。 我最初嘗試“ .before()”沒有成功,然后開始嘗試其他功能。

我無法發布圖像或添加其他鏈接來顯示屏幕截圖,暫時將其作為純文本URL放置,希望可以用來演示該問題。 https://www.dropbox.com/s/8jqf0l93n4tv8kf/Screenshot%202015-04-23%2006.32.18.png?dl=0

有人可以提供任何關於為什么在Chrome中正確執行而不是IE正確執行的指導或指示(我已經測試了IE8和IE11,但均未成功)。 謝謝。 -Eric

我相信這是您要嘗試做的事情:

$(document).ready(function (e) {
    $("a[name]").each(function() { // only selects tags with a name attribute
        var aName = $(this).attr('name');
        // .prepend() adds inside the element, .before() adds outside of it
        $(this).before("<span class='anchorfix' id='" + aName + "'></span>");
    });
});

http://jsfiddle.net/mp2z7hhu/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM