我正在创建一个Jquery Mobile应用程序,并且有一个包含15个左右的div的页面,我试图制作一个过滤系统,这样当你按下某个按钮时,这些div中的一些根据班级消失。有3组,他们都有一个"所有"类来显示总共4个类的所有内容。
不幸的是,即使我为jquery mobile设置了一个jsfiddle,当我把它放到我的应用程序中时,我使用的大部分j都不会起作用。它似乎无法正常工作。
我想用
FindElements
但这并不起作用,而function show(target) {
document.getElementsByClassName(target).style.display = 'block';
}
function hide(target) {
document.getElementsByClassName(target).style.display = 'none';
}
似乎工作正常。但显然我只能隐藏/显示每个按钮1个div ..
我想知道是否有一个解决这个或者我应该尝试的完全不同的东西?
以下是我所拥有的内容:http://jsfiddle.net/tzcx7gky/ 它在jsfiddle中完全被破坏但它在我的代码中工作正常,这很奇怪..
答案 0 :(得分:1)
getElementsByClassName
返回一个元素数组。所以你必须对数组进行迭代,然后在每个数组上设置display属性。由于您已经在使用jQuery,因此您可以使用它来为所有元素执行此操作。
function show(target) {
/* jQuery uses CSS selectors to grab elements
so we have to prefix the target with "."
Alternativley we could pass in the whole selector in the
function so we don't have to prefix it e.g.
show('.all')
$(target).show();
*/
$("."+target).show();
}
function hide(target) {
$("."+target).hide();
}
这是vanilla js框架中的相同实现
function show(target) {
var elements = document.getElementsByClassName(target);
elements.forEach(function(element){element.style.display = 'block';});
}
function hide(target) {
var elements = document.getElementsByClassName(target);
elements.forEach(function(element){element.style.display = 'none';});
}
请注意getElementById
返回单个元素,因为id是唯一的,并且页面上应该只有一个带有一个id的元素。这就是它为你工作的原因。
答案 1 :(得分:1)
您不需要单独的hide
- show
功能。以下将照顾所有。
$('a').on("click",function()
{
$("#scroll_content div").hide(); // initially hide all divs inside the element with id = scroll_content
var target = $(this).text().toLowerCase(); // find the class you wish to show using the text of the a tag clicked ( I would prefer using data-attr in this case but I'll leave the choice upto you.
$("." + target).show(); // show the element with the class target.
});