gpt4 book ai didi

javascript - 更改文本并将 HTML 添加到标签内复选框的文本

转载 作者:行者123 更新时间:2023-12-01 00:35:24 26 4
gpt4 key购买 nike

使用普通的 JS,当输入嵌套在标签标记中时,是否有一种方法能够更改出现在复选框旁边的文本内容?具体是在文本中添加 HTML 链接吗?

我可以毫无问题地更改文本,但将内容设置为显示 HTML 最终会将 HTML 渲染到屏幕上。因此,在下面的示例中,我希望将条款和条件文本设为链接。

<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>

我已经使用过节点和同级节点,虽然我可以更改文本,但会发生以下两种情况之一 - 我要么最终覆盖标签标记之间的所有内容,从而杀死复选框。

或者我的 anchor 标记被渲染到屏幕上而不是被解释。

有什么想法我哪里出错了吗?

这是我正在尝试的最新代码:

let terms = document.querySelector('#custom_field');

if(terms){

terms.nextSibling.innerHTML = "I have read and agree to the <a href='#'>terms and conditions</a>";
}

注意:由于我的 CMS 的限制,我无法直接编辑标签内容以插入相关 HTML。所以我需要按照第一个代码块进行操作。

最佳答案

innerHTML 不起作用,因为 terms.nextSiblingText节点,它没有 innerHTML 属性。

您需要split标签的 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>

关于javascript - 更改文本并将 HTML 添加到标签内复选框的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58173683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com