<li ondblclick="editThisTag(this)" title="New Account0123" class="select2-selection__choice">
<span class="select2-selection__choice__remove" role="presentation">×</span>
Testing Text
</li>
我想在点击按钮时替换<li>
标记“测试文字”中的文字。
<li>
标记包含<span>
标记,普通文本为子标记。 <span>
标记应保持原样,只需使用jQuery更改“测试文本”文本。
答案 0 :(得分:2)
获取span
内的li
,然后获取文本节点并更新文本
$('#change').click(function() {
$('li.select2-selection__choice')
// get the span inside, and use `[0]` to get dom object
.find('span')[0]
// get next node after span, which is text node
.nextSibling
// update the text content with new value
.textContent = 'text';
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="change">Change Text</button>
<ul>
<li ondblclick="editThisTag(this)" title="New Account0123" class="select2-selection__choice">
<span class="select2-selection__choice__remove" role="presentation">×</span>
Testing Text
</li>
</ul>
&#13;
或使用 contents()
, filter()
和 replaceWith()
$('#change').click(function() {
$('li.select2-selection__choice')
// get all nodes including text node and comment node
.contents()
// filter to get only text node and which is not empty
.filter(function() {
return this.nodeType === 3 && this.nodeValue.trim().length;
})
// replace it with new text
.replaceWith('text');
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="change">Change Text</button>
<ul>
<li ondblclick="editThisTag(this)" title="New Account0123" class="select2-selection__choice">
<span class="select2-selection__choice__remove" role="presentation">×</span>
Testing Text
</li>
</ul>
&#13;
答案 1 :(得分:1)
具有查找要更改的文本的功能。
jQuery("li").text(function () {
return jQuery(this).text().replace("Testing Text", "hello world");
});
https://jsfiddle.net/o9va6mqe/
工作小提琴^
答案 2 :(得分:0)
用标签附上您要更改的文本,以便指定li的哪个部分将更改。这样做。
$('button#changeText').click(function() {
$('li.select2-selection__choice').find('font').html('HELLO WORLD');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="changeText">Change Text</button>
<li title="New Account0123" class="select2-selection__choice">
<span class="select2-selection__choice__remove" role="presentation">×</span>
<font>Testing Text</font>
</li>
&#13;