2017-02-13 123 views
1

我有一些在各個地方都有標籤<ins>...</ins>的html。我希望能夠在具有這些標籤的行的開頭添加一些內容。當我說「行」時,我的意思是有<br>標籤(不是<br/>標籤)以及。添加到行的開頭

這裏的一些(彌補)HTML:

It was a very nice day in my home town.<br> 
Then suddenly a <ins>dragon</ins> came!<br> 
This <ins>dragon</ins> was absolutely <ins>terrifying</ins>,<br> 
and he made everyone flee. The end. 

我已經試過幾件事情。第2行是最接近的,但我應該使用類似於第3行的內容,但它並沒有做到這一點。

$("ins").each(function() { 
$(this).prev().after("&rarr; "); // this almost works, but inserts an extra → in line 3 
$(this).closest("br").after("&rarr; "); // not sure why this doesn't work 
}); 

結果應該是這樣的:

It was a very nice day in my home town. 
→ Then suddenly a <ins>dragon</ins> came! 
→ This <ins>dragon</ins> was absolutely <ins>terrifying</ins>, 
and he made everyone flee. The end. 

回答

0

指定內部prev()方法選擇器,以避免選擇任何其他標記。 closest()方法用於獲取最接近的祖先元素而不是兄弟。

$("ins").each(function() { 
 
    $(this).prev('br').after("&rarr; "); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
It was a very nice day in my home town. 
 
<br>Then suddenly a <ins>dragon</ins> came! 
 
<br>This <ins>dragon</ins> was absolutely <ins>terrifying</ins>, 
 
<br>and he made everyone flee.

+1

唉,我不知道你可以添加元素名稱上一個()。這很好,謝謝。我會在一分鐘內將其標記爲答案。 – theglossy1

相關問題