[英]Extreme JavaScript newbie - combining functions
请原谅我缺乏知识,我才刚刚开始学习。 有一个无序列表通过包含文件被拉入网页。 某些页面只应显示该无序列表中的某些列表项。 所以开发人员提出的解决方案很简单,通过在每个页面上都有一个脚本来隐藏您不想看到的内容,如下所示:
myFunction();
function myFunction() {
var list = document.getElementsByClassName("content")[0];
list.getElementsByTagName("li")[0].style.display="none";
list.getElementsByTagName("li")[1].style.display="none";
list.getElementsByTagName("li")[2].style.display="none";
list.getElementsByTagName("li")[3].style.display="none";
}
现在看看这个站点,将它作为一个长的滚动页面而不是多个页面更有意义,但显然这不适用于此脚本。 有没有一种方法可以在页面上包含多个这样的实例,并使用类似的逻辑,但是让每个包含的实例只显示无序列表中的某些列表项,也许是通过将每个实例包装在一个 ID 中并以该 ID 为目标?
例如:
<div id="one">
#include virtual="/content.html"
</div>
<div id="two">
#include virtual="/content.html"
</div>
其中 content.html 包含无序列表,但 div id one 仅显示该列表中的某些列表项,而 div id two 显示该列表中的某些(不同)列表项?
我希望这是有道理的。 再次,如果我没有很好地解释这一点,我们深表歉意。 非常感谢任何指导。
谢谢!
您正在寻找的架构是一个过滤器 function - 您一次获取一个项目列表 go ,如果您不想保留它们,请将它们取出。 您需要以一种概括任何列表和任何保留/不保留标准的方式编写此代码,然后使用您想到的特定列表和标准运行该 function。
所以,像这样:
<div id="one">
#include virtual="/content.html"
</div>
<div id="two">
#include virtual="/content.html"
</div>
<script>
// listDivId: The "id" of the div the list is under
// predicate: A function that takes the list item, and its index
// in the list, and returns either true or false depending on
// whether it should still be there
function filterContent(listDivId, predicate) {
// First get the div you want to filter, if it's not there, return
const listDiv = document.getElementById(listDivId);
if (listDiv === null) return;
// Then, get the list itself
const list = listDiv.getElementsByClassName("content")[0].getElementsByTagName("li");
// The "list" variable is now an array of "li" items, with a different
// item from list[0] to list[list.length - 1]. Use this while loop to
// go through each of them once
let i = 0;
while (i < list.length) {
// Call the predicate. If it returns false, hide the item.
if (!predicate(list[i], i)) {
list[i].style.display = "none";
}
i = i + 1;
}
}
// Now define our predicates.
function shouldAppearInOne(element, i) {
return i >= 0 && i < 3;
}
function shouldAppearInTwo(element, i) {
return i >= 3 && i < 6;
}
// Once we have both of those, call the filter function with those predicates
filterContent("one", shouldAppearInOne);
filterContent("two", shouldAppearInTwo);
</script>
顺便说一句,你提到content.html
是动态生成的——坦率地说,这个过滤的东西实际上放在生成content.html
的代码中会更好。 不是在你不想出现的列表项上设置display = none
,而是在浏览器有机会对它们进行排序之前写下你确实想要的项目:
let i = 0;
while (i < list.length) {
// If we do want to include it, write the <li> element
// (note that this assumes that `list` is just the text in the elements)
if (predicate(list[i], i) {
document.write("<li>" + list[i] + "</li>");
}
i = i + 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.