简体   繁体   English

如果选中其中一个单选按钮,如何更改两段中的文本? JS

[英]How to change text in two paragraphs if one of the radio buttons is checked? JS

I have a form where based on which radio button is checked (Metric or Imperial), the two paragraphs should display either KG + CM or LBS + IN.我有一个表格,根据选中的单选按钮(公制或英制),两个段落应显示 KG + CM 或 LBS + IN。 Right now it just displays KG or LBS twice.现在它只显示 KG 或 LBS 两次。 Looking for a solution in vanilla JS.在 vanilla JS 中寻找解决方案。 This is for a calculator I am working on.这是我正在研究的计算器。

 const paragraphWeightElement = document.querySelector(".js-paragraphWeight"); const paragraphHeightElement = document.querySelector(".js-paragraphHeight"); const form = document.querySelector(".js-form"); form.addEventListener("input", (event) => { paragraphWeightElement.innerText = event.target.value; paragraphHeightElement.innerText = event.target.value; });
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script defer src="js/script.js"></script> <link href="css/style.css" rel="stylesheet" /> </head> <body> <form class="js-form"> <ul> <li> <label> <input class="js-metric" type="radio" value="KG" name="weight" /> Metric </label> </li> <li> <label class="form__label"> <input class="js-imperial" type="radio" value="LBS" name="weight" /> Imperial </label> </li> </ul> </form> <p class="js-paragraphWeight"></p> <p class="js-paragraphHeight"></p> </body> </html>

You need to not work with event.target but rather find the element checked.您不需要使用event.target而是找到已检查的元素。

For the unit lookup, use a simple lookup map.对于单位查找,请使用简单的查找地图。

 const paragraphWeightElement = document.querySelector(".js-paragraphWeight"); const paragraphHeightElement = document.querySelector(".js-paragraphHeight"); const form = document.querySelector(".js-form"); const unitLookupMap = { metric: { weight: 'kg', height: 'meters' }, imperial: { weight: 'lbs', height: 'yards' }, } form.addEventListener("input", (event) => { const checked = form.querySelector('[name=units]:checked'); paragraphWeightElement.textContent = unitLookupMap[checked.value].weight; paragraphHeightElement.textContent = unitLookupMap[checked.value].height; });
 <form class="js-form"> <ul> <li> <label> <input class="js-metric" type="radio" value="metric" name="units" /> Metric </label> </li> <li> <label class="form__label"> <input class="js-imperial" type="radio" value="imperial" name="units" /> Imperial </label> </li> </ul> </form> <p class="js-paragraphWeight"></p> <p class="js-paragraphHeight"></p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM