jQuery - insertBefore()用于原始文本

时间:2017-02-13 09:41:50

标签: javascript jquery html

我使用jQuery 1.11.2和jQuery-migrate 1.2.1。以下是我尝试做的简单示例:

https://jsfiddle.net/bek3wrug/

我想在页面上的某个元素之前插入一些文本(未完全包装到HTML标记中),jQuery只插入包含在HTML标记内的部分。 我无法使用prepend(),因为我不想在内插入某些元素,我需要在之前插入

有没有办法让jQuery插入所有文本,而不仅仅包装到HTML标签中?

2 个答案:

答案 0 :(得分:3)

使用函数before

$("#mySpan").before("Raw text to insert. <span>Text inside span to insert. </span>")

示例:

&#13;
&#13;
$("#mySpan").before("Raw text to insert. <span>Text inside span to insert. </span>")
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
<span id="mySpan">Original text</span>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

由于它包含textNode,因此您需要使用jQuery.parseHTML方法,该方法会生成一组节点。否则它将被解释为选择器,因为没有使用字符串选择任何内容,所以不会发生任何事情。

$($.parseHTML("Raw text to insert. <span>Text inside span to insert. </span>")).insertBefore("#mySpan")

参考:Creating new elements using jQuery

$($.parseHTML("Raw text to insert. <span>Text inside span to insert. </span>")).insertBefore("#mySpan")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
  <span id="mySpan">Original text</span>
</div>

或使用before()方法。

$("#mySpan").before("Raw text to insert. <span>Text inside span to insert. </span>")

$("#mySpan").before("Raw text to insert. <span>Text inside span to insert. </span>")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
  <span id="mySpan">Original text</span>
</div>