簡體   English   中英

使用jQuery替換li標簽內的文本

[英]Replace text inside li tag using jQuery

<li ondblclick="editThisTag(this)" title="New Account0123" class="select2-selection__choice">
    <span class="select2-selection__choice__remove" role="presentation">×</span>
    Testing Text
</li>

我想替換按鈕上單擊<li>標記“ Testing Text”內的文本 <li>標記具有<span>標記,普通文本作為子代。 <span>標記應保持不變,只需使用jQuery單擊按鈕即可更改“測試文本”文本。

獲取li內的span ,然后獲取其后的文本節點並更新文本

 $('#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'; }) 
 <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> 


或以下方法,使用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'); }) 
 <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> 

具有查找要更改的文本的功能。

jQuery("li").text(function () {
    return jQuery(this).text().replace("Testing Text", "hello world"); 
});

https://jsfiddle.net/o9va6mqe/

工作提琴^

用標簽將要更改的文本括起來,以便您可以指定li的哪一部分將被更改。 像這樣做。

 $('button#changeText').click(function() { $('li.select2-selection__choice').find('font').html('HELLO WORLD'); }); 
 <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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM