Vanilla Javascript多个相同的选择,当您选择一个选项时,所有其他选择都会更改为相同的选项



如果我们在同一页面中有3个相同的选择,但在页面的不同部分

<div>
<select>
<option value="london">London</option>
<option value="paris">Paris</option>
</select>
</div>
<div>
<select>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
</select>
</div>
<div>
<p> hello </p>
</div>
<div>
<p> This is a random sentence </p>
</div>
<select>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
</select>
<div>
<p> Bye </p>
</div>
<div>
<p> This is a random second sentence </p>
</div>
<select>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
</select>

我希望,如果我在第一次选择中选择例如2;两个";也这可能吗?谢谢:(

我会委派。

将容器更改为最近的静态容器,容纳所有选定的或包装它们的

在这里,我给出了我想同步一个类的选择

const selects = document.querySelectorAll("select.sync");
document.addEventListener("change", function(e) {
const tgt = e.target;
if (tgt.classList.contains("sync")) {
const idx = tgt.selectedIndex;
selects.forEach(sel => sel.selectedIndex = idx);
}
})
<div>
<select>
<option value="london">London</option>
<option value="paris">Paris</option>
</select>
</div>
<div>
<select class="sync">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
</select>
</div>
<div>
<p> hello </p>
</div>
<div>
<p> This is a random sentence </p>
</div>
<select class="sync">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
</select>
<div>
<p> Bye </p>
</div>
<div>
<p> This is a random second sentence </p>
</div>
<select class="sync">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
</select>

相关内容

  • 没有找到相关文章

最新更新