我怎样才能返回2个值与getElementsByClassName()?
这个问题在这里已经有了答案:
使用循环:
<!DOCTYPE html>
<html>
<body>
<div class="example">First div element with class="example".</div>
<div class="example">Second div element with class="example".</div>
<p>Click the button to change the text of the first div element with class="example" (index 0).</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
for(var i = 0; i < x.length; i++)
x[i].innerHTML = "Hello World!";
}
</script>
</body>
</html>
您必须使用循环才能影响所有元素:
function myFunction() {
var x = document.getElementsByClassName("example");
for (var i = 0; i < x.length; i++)
x[i].innerHTML = "Hello World!";
}
你可以使用querySelectorAll
方法:
function myFunction() {
var divs = document.querySelectorAll('.example');
[].forEach.call(divs, function(div) {
div.innerHTML = "Hello World!";
});
}
链接地址: http://www.djcxy.com/p/24545.html
上一篇: How can i return 2 values with getElementsByClassName()?