繁体   English   中英

要显示的随机 p 标签

[英]Random p tag to display

我试图恢复到我在使用 jQuery 的地方所做的一些工作。 我想改用 vanilla JS。 我已经注释掉了正在运行的 jQuery,以便更好地理解我想要实现的目标。

var quotes = document.getElementsByClassName("quotes");

 document.getElementById("generate").addEventListener("click", function (event) {
  var random = Math.floor(Math.random() * quotes.length);
  quotes.style.visibility = "hidden";
  quotes[random].style.visibility = "visible";
  //$('.quotes').hide().eq(random).show();
});

我希望在运行代码时显示一个随机段落标签。 任何帮助将非常感激。

quotes是一个类似数组的对象,因此没有style属性。

您可以改为遍历数组中的每个并更改其visibility属性。

此外,您可以在循环中使用三元运算符将 1 项设置为可见。

for(var i = 0; i < quotes.length; i++){
   quotes[i].style.visibility = (i==random) ? "visible" : "hidden";
}

严格来说,如果您希望将 jQuery 实现复制到 VanillaJS 中,那么您应该更改的是display属性,而不是visibility

for(var i = 0; i < quotes.length; i++){
   quotes[i].style.display = (i==random) ? "block" : "none";
}

这里的工作示例: https : //jsfiddle.net/1cog9t3c/1/


 var quotes = document.getElementsByClassName("quotes"); document.getElementById("generate").addEventListener("click", function (event) { var random = Math.floor(Math.random() * quotes.length); for(var i = 0; i < quotes.length; i++){ quotes[i].style.display = (i==random) ? "block" : "none"; } });
 <div class="quotes"> test </div> <div class="quotes"> test 2 </div> <div class="quotes"> test 3 </div> <button id="generate"> gen </button>

代替

var quotes = document.getElementsByClassName("quotes");

var quotes=document.getelemetsByid("quotes").innerhtml;

您的quotesHTMLCollection ,因此您需要对其进行循环。

您可以使用Array.prototype.forEach.call对数组的每个元素调用函数:

 var quotes = document.getElementsByClassName("quotes"); document.getElementById("generate").addEventListener("click", function(event) { var random = Math.floor(Math.random() * quotes.length); Array.prototype.forEach.call(quotes, function(quote) { quote.style.visibility = "hidden"; }); quotes[random].style.visibility = "visible"; });
 <div class="quotes">quote1</div> <div class="quotes">quote2</div> <div class="quotes">quote3</div> <div class="quotes">quote4</div> <div id="generate"> Generate </div>

暂无
暂无

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

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