我有一些html在不同的地方都有<ins>...</ins>
标记。我希望能够在这些标签的哪一行的开头添加一些东西。当我说“行”时,我的意思是也有<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("→ "); // this almost works, but inserts an extra → in line 3
$(this).closest("br").after("→ "); // 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 :(得分:0)
在prev()
方法中指定选择器以避免选择任何其他标记。 closest()
方法用于获取最接近的祖先元素而不是兄弟元素。
$("ins").each(function() {
$(this).prev('br').after("→ ");
});
<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.