Javascript 如何在已单击单选按钮时自动添加颜色?

Javascript 如何在已单击单选按钮时自动添加颜色?,javascript,jquery,html,css,svg,Javascript,Jquery,Html,Css,Svg,这是我当前的svg图表 这是我想要的,如果单击单选按钮,框将自动填充为黑色 这是我为box编写的svg代码 <svg class="teeth" id="svg" width="400px" height="300px" viewBox="0 0 400 300" preserveAspectRatio="xMidYMid meet"> <!-- upper right 8 --> <g id="premolar-group">

这是我当前的svg图表

这是我想要的,如果单击单选按钮,框将自动填充为黑色

这是我为box编写的svg代码

<svg class="teeth" id="svg" 
 width="400px" height="300px" viewBox="0 0 400 300" preserveAspectRatio="xMidYMid meet">
    <!-- upper right 8 -->
    <g id="premolar-group">
        <rect x="75" y="75" stroke="black" id="occlusal" style="stroke-width: 5px;" width="150" height="150" fill="white"/>
        <polygon stroke="black" id="buccal" style="stroke-width: 5px;" points="0 0 300 0 225 75 75 75" fill="white" />
        <polygon stroke="black" id="mesial" style="stroke-width: 5px;" points="300 0 300 300 225 225 225 75" fill="white" />
        <polygon stroke="black" id="palatal" style="stroke-width: 5px;" points="300 300 0 300 75 225 225 225" fill="white" />
        <polygon stroke="black" id="distal" style="stroke-width: 5px;" points="0 300 0 0 75 75 75 225" fill="white" />
        <polygon stroke="black" class="distal cross1" style="stroke-width: 5px;" fill="white" />
        <polygon stroke="black" class="distal cross2" style="stroke-width: 5px;" fill="white" />

<input type="radio" name="browser" value="Y" id="answer">


    </g>

</svg>


当单选按钮已被单击时,有人能帮助您如何用黑色填充框吗?

您首先需要获取SVG中要更新的元素。在您的例子中,它看起来就像是
多边形
s和
矩形
元素

一旦有了它,就可以使用
fill
属性为元素着色

const radioButton=document.getElementById('answer');
radioButton.addEventListener('change',e=>{
如果(e.target.value=='Y'){
const polygons=document.querySelectorAll('svg polygon,svg rect');
polygons.forEach(p=>p.setAttribute('fill','red');
}
});


我认为您不能将
输入像这样放入SVG中。因此@Paulie\u D输入将位于SVG的外部?您可以使用javascript向按钮添加事件侦听器,如果选中,您可以通过更改
fill=“white”来更改SVG的颜色
转换为不同的颜色。更常见的方法是在HTML中将输入置于SVG之前,然后使用
:checked+
设置SVG的样式。如果您只需重新排列元素,就可以在没有任何JavaScript的情况下完成这项工作。我会将此添加到我的答案中。sir@mwhilson如果我单击单选按钮,我的所有SVG图表已经用红色填充,我有32个图表。先生,你能根据一张SVG图表的id重新编辑你的答案吗?我只是一名学生,试图了解SVG和javascriptI。我只有13个声誉。我唯一能做的就是接受答案,所以你希望你的svg有一个不同于红色的颜色?你想要什么颜色的?