简体   繁体   English

获取多个元素:仅返回最后一个

[英]Getting multiple elements: only return the last one

I'm trying to get multiple elements (input) through a function via className and element name but in both cases only return the last element. 我试图通过一个函数通过className和element name获取多个元素(输入),但在两种情况下都只返回最后一个元素。 Even though I clicked the first two checkboxs the alert is "bye is false". 即使我单击了前两个复选框,警报仍然是“再见是错误的”。 This should show like "true" the element at the moment when I clicked on it, but doesn't happen. 当我单击该元素时,该元素应显示为“ true”,但不会发生。

This is the HTML: 这是HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
   <input type="checkbox" name="inPut" value="hi" class="greeting" /> Hi!!
  </br>
  <input type="checkbox" name="inPut" value="good" class="greeting" /> Good Morning!!
  </br>
  <input type="checkbox" name="inPut" value="bye" class="greeting" /> Bye!!
</body>
</html>

I tried to get them using classNAME: 我试图使用classNAME来获取它们:

var inNer = document.getElementsByClassName('greeting');


    for (var i = 0; i < inNer.length; i++){

        prueba = inNer[i];
        var test = prueba.onclick = showIn;

      }


    function showIn(){

      var rex = prueba;
      alert('\''+rex.value+'\'' + ' es ' + rex.checked);
    }

And I tried get the elements through Name: 我尝试通过Name获取元素:

var inName = document.box.inPut;


for (var i = 0; i < inName.length; i++){

  var test = inName[i];
  var call = test.onclick = showIn;
}

function showIn(){

  var outPut = test;
  alert(outPut.value + ' is ' + outPut.checked);

}

Your showIn function is incorrect. 您的showIn函数不正确。 There's no need to assign prueba again. 无需再次分配prueba It should be: 它应该是:

function showIn() {
  alert('\'' + this.value + '\'' + ' es ' + this.checked);
}

Fiddle 小提琴

var inNer = document.getElementsByClassName('greeting');
for(var i=0; i<inNer.length; i++){
   inNer[i].onclick = showIn;
}
function showIn(){
   alert(this.value +" es "+ this.checked);
}

btw, </br> should be <br> || 顺便说一句, </br>应该是<br> || <br /> || <br /> || <br/> just not </br> <br/>只是</br>

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

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