1

请帮我替换下面的html代码

原始代码

<div class="multiAttType">
    <input type="radio" id="Radio7_1" value="Google">
    <label for="Radio7_1" class="radioChoice">Google</label>
</div>

<div class="multiAttType">
    <input type="radio" id="Radio7_2" value="Bing">
    <label for="Radio7_2" class="radioChoice">Bing</label>
</div>

在 PageLoad 上它应该更改为

<div class="multiAttType">
    <input type="radio" id="Radio7_1" value="Google">
    <span class="sameclass">Google <a href="https://www.google.com/">Link 1</a></span>
</div>

<div class="multiAttType">
    <input type="radio" id="Radio7_2" value="Bing">
    <span class="sameclass">Bing <a href="https://www.bing.com/">Link 2</a></span>
</div>
4

2 回答 2

0

这是一种静态方式

window.onload = function() {
	var multAtt = document.getElementsByClassName('multiAttType');
  
  for (var i = 0; i < multAtt.length; i++) {
  
  	var children = multAtt[i].children;
    
    for (var j = 0; j < children.length; j++) {
    	  
      if(children[j].innerHTML == 'Google' && children[j].tagName == 'LABEL') {
        multAtt[i].removeChild(multAtt[i].children[j]);
        multAtt[i].insertAdjacentHTML('afterend', '<span class="sameclass">Google <a href="https://www.google.com/">Link 1</a></span>');
      } else if ( children[j].innerHTML == 'Bing' && children[j].tagName == 'LABEL') {
				multAtt[i].removeChild(multAtt[i].children[j]);
        multAtt[i].insertAdjacentHTML('afterend', '<span class="sameclass">Bing <a href="https://www.bing.com/">Link 2</a></span>');
      }
      
    }
  }
}
<div class="multiAttType">
  <input type="radio" id="Radio7_1" value="Google">
  <label for="Radio7_1" class="radioChoice">Google</label>
</div>

<div class="multiAttType">
  <input type="radio" id="Radio7_2" value="Bing">
  <label for="Radio7_2" class="radioChoice">Bing</label>
</div>

于 2019-11-07T18:58:30.050 回答
0

您可以在 jquery 中使用 :contains() 选择器来实现这一点。

示例:$('label:contains("Google")')

现在使用 jquery 中的 replaceWith 函数替换 html 内容。

更新了代码片段以替换页面加载时的 html 内容。

function replaceHtml(){

$('label:contains("Google")').replaceWith('<span class="sameclass">Google <a href="https://www.google.com/">Link 1</a></span>')

$('label:contains("Bing")').replaceWith('<span class="sameclass">Bing <a href="https://www.bing.com/">Link 2</a></span>')

}


$(document).ready(function(){

//calling the replace function on page load
replaceHtml();

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="multiAttType">
    <input type="radio" id="Radio7_1" value="Google">
    <label for="Radio7_1" class="radioChoice">Google</label>
</div>

<div class="multiAttType">
    <input type="radio" id="Radio7_2" value="Bing">
    <label for="Radio7_2" class="radioChoice">Bing</label>
</div>


<button onclick="replaceHtml()">Replace</button>

于 2019-11-07T18:13:50.963 回答