如何简化这个JS函数

时间:2015-10-01 13:33:02

标签: javascript jquery

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

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

我不熟悉香草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);

    }
});

2 个答案:

答案 0 :(得分:1)

尝试调用两个段落1(closedview)和2(opensview):

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);
    }
});

答案 1 :(得分:0)

将普通内容放在一个函数中,并将差异作为参数传递,如下所示:

document.addEventListener('DOMContentLoaded', function() {
  myFunction('#closedview');
});

document.addEventListener('DOMContentLoaded', function() {
  myFunction('#openedview');
});

function myFunction(viewId) {
  var radioButtons = document.getElementsByName('viewangle');
  var paragraph = document.querySelector(viewId);

  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);
      }
    });
  }
}

或者与@ RobG的答案结合:将document.querySelector()的结果传递给myFunction()。

PS:@ Federico的回答实际上更清晰,更好:你只需要向DOMContentLoaded添加一个eventlistener ..