HTML5使用按钮js

时间:2017-11-13 22:01:14

标签: javascript html html5

我遇到了这个小麻烦:

<style>
p:empty {height:20px};
p:nth-child(4n+3) {background:black};
</style>    
</head>

<body>

<button onclick="f()">white</button>
<script>
function f() {
var x = document.getElementsByTagName("p");
x.style.backgroundColor = "white";
}
</script>

<p></p>
<p></p>
<p></p>
.... 

(有20段) 所以每第4段都有黑色背景,一切都很好。 我希望这个按钮在点击它之后将黑色切换回白色,但是它不起作用,我做错了什么?

4 个答案:

答案 0 :(得分:0)

正如评论中所述,您需要遍历这些元素。这很简单,只需使用forEach,如下所示。

function f() {
    var x = document.getElementsByTagName("p");
    Array.from(x).forEach(elem => elem.style.backgroundColor = "white");
}

答案 1 :(得分:0)

实际上 document.getElementsByTagName() 会返回HTMLCollection,您需要循环并应用该样式:

function f() {
  var paragraphs = document.getElementsByTagName("p");
  Array.from(paragraphs).forEach(function(x){
       x.style.backgroundColor = "white";
  });
}

<强>演示:

&#13;
&#13;
function f() {
  var paragraphs = document.getElementsByTagName("p");
  Array.from(paragraphs).forEach(function(x){
       x.style.backgroundColor = "white";
  });
}
&#13;
p:empty {
  height: 20px;
}

p:nth-child(4n+3) {
  background: black;
}
&#13;
<button onclick="f()">white</button>

<p>A</p>
<p>B</p>
<p>C</p>
<p>A</p>
<p>B</p>
<p>C</p>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

从我看到的情况来看,您的函数f会调用document.getElementsByTagName("p")document.getElementsByTagName返回一个HTMLCollection对象,该对象没有style属性,并且设置它不会执行任何操作。你想要做的是遍历HTMLCollection的项目并为每个元素设置样式,如下所示:

// This function will make all <p> elements have a white background
function f() {
    var paragraphs = document.getElementsByTagName("p");
    for (var i = 0; i < paragraphs.length; i++) {
        paragraphs[i].style.backgroundColor = "white";
    }
}

有关详细信息,请参阅Mozilla的HTMLCollectiondocument.getElementsByTagName文档。

答案 3 :(得分:0)

所以这里的问题是你正在使用getElementsByTagName,它会返回一个包含&#34; p&#34;的所有实例的数组。元件。当你说的时候 x.style.backgroundColor =&#34; white&#34;

你需要指定哪个&#34; p&#34;在你想要改变的数组中,就像我在下面一样 x [3] .style.backgroundColor =&#34; white&#34;

......你可能会做这样的事情

function f() {
var x = document.getElementsByTagName("p");

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

 x[i].style.backgroundColor = "white";

 }
}