<a class="link">
<p class="paragraph">This is some text</p>
<p class="paragraph">This is some more text</p>
<p class="paragraph">And some more</p>
</a>
到這一點。我嘗試使用追加和合並,但我無法弄清楚。
<a class="link">
<p class="paragraph">This is some text</p>
<p class="paragraph">This is some more text</p>
<p class="paragraph">And some more</p>
</a>
到這一點。我嘗試使用追加和合並,但我無法弄清楚。
由於text
方法返回一個元素的文本內容和它的後代,你可以使用:
var link = $("a.link");
link.text(link.text());
從文檔:
獲取每個元素的合併文本內容在匹配 元素集合中,包括它們的後代。
更新(見註釋)
在這需要應用到多個.link
元素的情況下,你可以使用each
:
$("a.link").each(function() {
$(this).text($(this).text());
});
試試這個
$(document).ready(function(){
var concatText = "";
$("p.paragraph").each(function(){
concatText = concatText + " " + $(this).text()
});
$("a.link").html(concatText);
});
這將工作:
$("a.link").text(function(i,text){
return text;
});
而另一種方式(未測試):
// you can optionally filter to
// only p elements too with
// .children("p")
$("a.link").children().contents().unwrap();
這裏是第二的另一個變化:爲清楚起見剛一說明:
所有這些
$("a.link p").contents().unwrap();
編輯解決方案適用於多個元素。第一種解決方案是一種相對罕見的語法,可用於大多數jQuery setter函數。它在每個匹配的元素上運行回調,並將屬性/屬性的值設置爲回調返回的值。
但是如果'a.link'匹配多個元素會發生什麼? – 2012-04-04 21:34:27
多優雅的解決方案 – DG3 2012-04-04 21:34:29
@FrédéricHamidi - 然後它將取代每個文本與所有文本。我認爲這隻適用於一個元素。請參閱編輯。 – 2012-04-04 21:35:44