gpt4 book ai didi

javascript - 影子 DOM : Elements attached to shadow DOM not rendering

转载 作者:行者123 更新时间:2023-12-02 22:01:13 28 4
gpt4 key购买 nike

我试图了解单选按钮如何在影子 dom 中工作。我有一个脚本标签,我将一个影子 DOM 附加到一个元素,然后附加一些单选按钮。我的问题是单选按钮未呈现。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>Radio Buttons:</p>
<div id="containter">

</div>

<script>
let shadowContainer = document.getElementById('containter');
shadowContainer.attachShadow({mode: 'open'});

let input1 = document.createElement('input');
input1.setAttribute("type", "radio");
input1.setAttribute("id", "1");
input1.setAttribute("name", "group");
input1.setAttribute("value", "1");

let input2 = document.createElement('input');
input2.setAttribute("type", "radio");
input2.setAttribute("id", "2");
input2.setAttribute("name", "group");
input2.setAttribute("value", "2");

let input3 = document.createElement('input');
input3.setAttribute("type", "radio");
input3.setAttribute("id", "3");
input3.setAttribute("name", "group");
input3.setAttribute("value", "3");

shadowContainer.appendChild(input1);
shadowContainer.appendChild(input2);
shadowContainer.appendChild(input3);
</script>
</body>
</html>

最佳答案

问题是您没有将元素添加到shadowDom,而是将它们添加到div。只需存储 .attachShadow 的返回值并附加到该值即可。这是您执行此操作的示例。

let shadowContainer = document.getElementById('containter');
// store the reference
let container = shadowContainer.attachShadow({
mode: 'open'
});

let input1 = document.createElement('input');
input1.setAttribute("type", "radio");
input1.setAttribute("id", "1");
input1.setAttribute("name", "group");
input1.setAttribute("value", "1");

let input2 = document.createElement('input');
input2.setAttribute("type", "radio");
input2.setAttribute("id", "2");
input2.setAttribute("name", "group");
input2.setAttribute("value", "2");

let input3 = document.createElement('input');
input3.setAttribute("type", "radio");
input3.setAttribute("id", "3");
input3.setAttribute("name", "group");
input3.setAttribute("value", "3");

// append to the reference
container.appendChild(input1);
container.appendChild(input2);
container.appendChild(input3);
<p>Radio Buttons:</p>
<div id="containter">

</div>

关于javascript - 影子 DOM : Elements attached to shadow DOM not rendering,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59868970/

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