ps0*_*604 29 javascript jquery
在这个插件我有一个div包含一些文本和一个span文本.
我的目标是改变文本div,而不改变文本span.
我尝试使用jQuery,但问题是整个div文本发生了变化,还取代了span文本,任何想法?
HTML
<div id="id1">some text to change <span>THIS TEXT STAYS</span></div>
Run Code Online (Sandbox Code Playgroud)
使用Javascript:
$( document ).ready(function() {
var id1 = $("#id1");
id1.text("New Text");
});
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 34
这是jQuery对你没有多大帮助的罕见地方之一.你想直接进入Text节点div:
$( document ).ready(function() {
var id1 = $("#id1");
// The [0] accesses the raw HTMLDivElement inside the jQuery object
// (this isn't accessing internals, it's documented).
// The `firstChild` is the first node within the `div`, which is
// the text node you want to change. `nodeValue` is the text of the
// Text node.
id1[0].firstChild.nodeValue = "New Text";
});Run Code Online (Sandbox Code Playgroud)
<div id="id1">some text to change <span>THIS TEXT STAYS</span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
或者ready根本不使用jQuery(除了):
$( document ).ready(function() {
var id1 = document.getElementById("id1");
id1.firstChild.nodeValue = "New Text";
});Run Code Online (Sandbox Code Playgroud)
<div id="id1">some text to change <span>THIS TEXT STAYS</span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
vij*_*ayP 10
请看看这种方法:
$( document ).ready(function() {
$("#id1").contents().get(0).nodeValue = "New Text 1 "
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="id1">some text to change <span>THIS TEXT STAYS</span></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5264 次 |
| 最近记录: |