我有这个HTML:
<div class="test">Orange <span class="is">is</span> my favorite color.</div>
我只想替换
Orange
(及其后的空格)。使用.text()
无效,因为它会选择整个强度。我该怎么做呢?
最佳答案
使用jQuery比使用本机DOM更难,因此,如果使用jQuery,则必须使用jQuery的数组索引将元素转换为本机DOM。
基本上,我们需要做的是更改第一个文本节点。 jQuery在文本节点上并不是很好,这就是为什么我们在这里使用DOM的原因:
//This gets the div.test element using jQuery:
var testDiv = $("div.test");
function changeColor(color) {
/* The following function changes the value of the first text node within testDiv: */
//This converts testDiv from a jQuery element to a regular DOM element. This is because jQuery isn't really meant to be handling stuff like text nodes, so doing this with the regular DOM will just be much easier.
var domElement = testDiv[0];
//Now, just change the value of the first text node:
domElement.childNodes[0].nodeValue = color;
}
//Now, as you can see if you click div.test, we can replace the color mentioned in div.test using changeColor():
testDiv.click(function() {
changeColor("Blue ");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Orange <span class="is">is</span> my favorite color.</div>