2010-12-21 39 views
2

使用jQuery,您將如何替換每個<acronym>標記與<abbr>使用jQuery的HTML5首字母縮略詞標記替換

+0

不知道你爲什麼會想這樣做jQuery的,或JavaScript句號。正確的標記應該寫入HTML文檔 - 或者甚至更好的是,在XML或JSON(服務器端)保留術語詞彙表,並通過用縮寫標記包裝HTML中的術語文本節點實例。 – DigiKev 2012-07-06 22:55:19

回答

3
$('acronym').each(function() { 
    var $this = $(this); 
    $this.before('<abbr>' + $this.html() + '</abbr>'); 
    $this.remove(); 
}); 
+0

比我的簡單。它適用於所有情況下的99%,因此+1 – Blender 2010-12-21 02:50:54

+2

您也想要複製任何屬性:http://stackoverflow.com/questions/2048720/get-all-attributes-from-a-html-element -with-javascript-jquery – 2010-12-21 02:51:18

2

我想試試這個,但我不提供保修。

$('acronym').each(function(index) 
{ 
    var old = this; 
    var newElement = $("<abbr></abbr>"); 

    $.each(this.attributes, function(index) 
    { 
    $(newElement).attr(old.attributes[index].name, old.attributes[index].value); 
    }); 

    $(newElement).html(old.html()); 

    $(this).after(newElement).remove(); 
}); 

祝你好運,並告訴我它是否被破壞。如果它被破壞了,我會嘗試修復它。

+0

你忘了複製原始標籤的內容。 – sje397 2010-12-21 03:05:42

+0

現在您正在爲每個屬性複製一次內容? – sje397 2010-12-21 03:52:17

+0

年。我似乎無法做到正確... – Blender 2010-12-21 03:55:56

1

使用jQuery的replaceWith。我假設你只使用title屬性。

$("acronym").each(function(){//for each acronym element 
     var abbr = $("<abbr></abbr>");//create a new abbr element 
     var title = $(this).attr("title");//get the title attribute from the acronym element 
     abbr.attr("title",title);//add it to the new abbr element 
     abbr.html($(this).html());//add in the content of the acronym element 
     $(this).replaceWith(abbr);//replace the old with the new! 
    }); 

Try it!

1

東西線沿線的:

$('acronym').each(function(i, el) { 
    $(this).replaceWith($('<abbr></abbr>').html($(this).html())); 
}); 

http://jsfiddle.net/7H4G6/1/

編輯:你想複製過的屬性,如果您有任何...理所當然你沒有。

  • 基督教
1
$('acronym').each(function() { 
    $(this).replaceWith('<abbr>' + $(this).html() + '</abbr>'); 
}); 
1
$("acronym").each(function(idx,HTML) { 
    $(this).replaceWith('<abbr title="'+this.title+'">'+HTML+'</abbr>'); 
}); 
相關問題