3 回答
![?](http://img1.sycdn.imooc.com/54584ef20001deba02200220-100-100.jpg)
TA贡献1865条经验 获得超7个赞
innerHTML不起作用,因为terms.nextSibling是一个Text没有innerHTML属性的节点。
您需要根据“条款和条件”拆分标签Text节点,然后将该节点移动到链接中:
const terms = document.querySelector('#custom_field');
if (terms) {
const fullText = terms.nextSibling;
const link = document.createElement('a');
link.href = '#';
const tcIndex = fullText.textContent.indexOf('terms and conditions');
const termsText = fullText.splitText(tcIndex);
// If there's more text after "terms and conditions", you'll need to split again
// termsText.splitText('terms and conditions'.length);
fullText.parentElement.insertBefore(link, termsText);
link.append(termsText);
}
<label for="custom_field">
<input type="checkbox" name="custom_field" id="custom_field" value="I have read the terms and conditions"> I have read the terms and conditions
</label>
![?](http://img1.sycdn.imooc.com/545865470001bf9402200220-100-100.jpg)
TA贡献2016条经验 获得超9个赞
为什么不添加额外的 HTML 标签?
<label for="custom_field">
<input type="checkbox" name="custom_field" id="custom_field">
// Added Span
<span id="result"> I have read the terms and conditions</span>
</label>
<script>
let terms = document.querySelector('#custom_field');
if(terms){
document.getElementById('result').innerHTML = "I have read and agree to the <a href='#'>terms and conditions</a>";
}
</script>
![?](http://img1.sycdn.imooc.com/54584cb50001e5b302200220-100-100.jpg)
TA贡献1851条经验 获得超5个赞
我相信这是使用纯 JavaScript 实现它的最基本方法。由于复选框后面有一个文本节点,因此您需要首先找到要替换的文本,然后将其替换为包含在可以包含 HTML 的新节点中的 HTML(现有文本节点不能转换)。
let terms = document.querySelector('label');
for (var i = 0; i < terms.childNodes.length; i++) {
var textNodeTrimmed;
if (terms.childNodes[i].nodeType === 3) textNodeTrimmed = terms.childNodes[i].nodeValue.trim()
if (textNodeTrimmed.length > 0 && textNodeTrimmed === "I have read the terms and conditions") {
var replacementNode = document.createElement('span');
replacementNode.innerHTML = "I have read and agree to the <a href='#'>terms and conditions</a>";
terms.childNodes[i].parentNode.insertBefore(replacementNode, terms.childNodes[i].nextSibling);
terms.childNodes[i].remove();
}
}
<label for="custom_field">
<input type="checkbox" name="custom_field" id="custom_field" value="I have read the terms and conditions"> I have read the terms and conditions
</label>
添加回答
举报