簡體   English   中英

Javascript - 如果標記包含特定文本,則替換文本

[英]Javascript - Replace text if tag contains specific text

我正在使用Wordpress,如果標簽包含特定文本,我需要替換文本。 我對Javascript不是很熟悉,所以我希望有人可以幫助我:)

這是我的html結構:

<tbody>
<tr class="tr1">
<td class="td1">
<a href="http://www.example.com">Name 1</a>
<strong class="quantity">× 1</strong>
</td>
<td class="td2">
<span class="span1">30$</span>
</td>
</tr>
</tbody>

我想要實現的是:

  • 如果span class =“span1”=“30 $”或span class =“span1”=“40 $”
  • 然后“名稱1”需要替換為“名稱2”
  • 如果不是(= span不是30或40),則腳本不能運行。
  • “名稱2”將與span = 30或40相同。

我希望我的解釋足夠清楚。 我試圖先自己搜索,我發現了一些功能,如getelement和innerHTML,但我沒有找到如何將它與我需要的結果相結合。

謝謝!

編輯:我想用特定的href =“http://www.example.com”定位標簽A.

您可以使用querySelector()querySelectorAll()querySelectorAll() closest()並執行類似的操作

 function changeTxt() { // get all spans var ele = document.querySelectorAll('.td2 .span1'); // iterate over the html element collection for (var i = 0; i < ele.length; i++) { // parse the text to get number // if symbol is in starting following will not work // var text = parseFloat(ele[i].innerHTML, 10); var text = parseFloat(ele[i].innerHTML.match(/\\d+(\\.\\d+)?/)[0], 10); // check the value is 30 or 40 if (text == 30 || text == 40) { // if true then get current tr and get anchor tag and update content var item = ele[i] // getting closest ancestor tr .closest('tr') // select a tag which have particular attribute value .querySelector('.tad1 a[href="http://www.example.com"]') // check item exists and update if (item) { item.innerHTML = 'Name 2'; // disabling click event (since disabled attribute will not work) //item.setAttribute('onClick', "return false;"); //or remove the href attribute item.removeAttribute('href'); // or // item.setAttribute('href','#'); } } } } changeTxt(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tbody> <tr class="tr1"> <td class="tad1"> <a href="http://www.example.com">Name 1</a> <strong class="quantity">× 1</strong> </td> <td class="td2"> <span class="span1">30.0$</span> </td> </tr> <tr class="tr1"> <td class="tad1"> <a href="http://www.example.com">Name 1</a> <strong class="quantity">× 1</strong> </td> <td class="td2"> <span class="span1">30.1$</span> </td> </tr> <tr class="tr1"> <td class="tad1"> <a href="http://www.example.com">Name 1</a> <strong class="quantity">× 1</strong> </td> <td class="td2"> <span class="span1">20$</span> </td> </tr> <tr class="tr1"> <td class="tad1"> <a href="http://www.example.com">Name 1</a> <strong class="quantity">× 1</strong> </td> <td class="td2"> <span class="span1">£30</span> </td> </tr> <tr class="tr1"> <td class="tad1"> <a href="#">Name 1</a> <strong class="quantity">× 1</strong> </td> <td class="td2"> <span class="span1">30$</span> </td> </tr> </tbody> </table> 

暫無
暫無

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

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