gpt4 book ai didi

javascript - 如何简化这个JS函数

转载 作者:行者123 更新时间:2023-11-27 23:48:52 27 4
gpt4 key购买 nike

是否可以将这两个功能合二为一?

我尝试在一个函数中使用多个选择器,但没有得到任何结果。

我对普通 JS 不熟悉。预先感谢您!

document.addEventListener('DOMContentLoaded', function() {

var radioButtons = document.getElementsByName('viewangle');
var paragraph = document.querySelector('#closedview');

for(var i=0;i< radioButtons.length;i++)
{
var elem = radioButtons[i];
elem.addEventListener('change',function(e){
console.log(paragraph);
if(paragraph.className)
paragraph.className = this.value;
else
paragraph.classList.add(this.value);
}
,false);

}
});

document.addEventListener('DOMContentLoaded', function() {

var radioButtons = document.getElementsByName('viewangle');
var paragraph = document.querySelector('#openedview');

for(var i=0;i< radioButtons.length;i++)
{
var elem = radioButtons[i];
elem.addEventListener('change',function(e){
console.log(paragraph);
if(paragraph.className)
paragraph.className = this.value;
else
paragraph.classList.add(this.value);
}
,false);

}
});

最佳答案

尝试调用两个段落1(关闭 View )和2(打开 View ):

document.addEventListener('DOMContentLoaded', function() {
var radioButtons = document.getElementsByName("viewangle");
var paragraph1 = document.getElementById("closedview");
var paragraph2 = document.getElementById("openedview");
for(var i=0;i< radioButtons.length;i++){
var elem = radioButtons[i];
elem.addEventListener('change',function(e){
console.log(paragraph1);
console.log(paragraph2);
if(paragraph1.className){ paragraph1.className = this.value; }else{ paragraph1.classList.add(this.value); }
if(paragraph2.className){ paragraph2.className = this.value; }else{ paragraph2.classList.add(this.value); }
}
,false);
}
});

关于javascript - 如何简化这个JS函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32888948/

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