使用JavaScript过滤DIV

时间:2019-06-19 03:32:33

标签: javascript html

我有这样的DIV

 <div *ngIf="viewModel != null" 
 id="filter_{{viewModel.countryId}}_{{viewModel.regionId}}" 
 class="filter_{{viewModel.countryId}}_{{viewModel.regionId}}">Some 
 text</div>

我跑步时会得到这样的DIV

   <div id="filter_1_123" class="filter_1_123">Some text</div>

我有多个这样的DIV

 <div id="filter_1_124" class="filter_1_124">Some text</div>

 <div id="filter_2_223" class="filter_2_223">Some text</div>

 <div id="filter_3_323" class="filter_3_323">Some text</div>

我要过滤以过滤器_1开头的div ID(我将1传递给选择选项)

当我选择1时必须显示

 <div id="filter_1_123" class="filter_1_123">Some text</div>
 <div id="filter_1_124" class="filter_1_124">Some text</div>

所有其他DIV应该被隐藏

再次通过“选择”选项,我仅将值123传递给了

  <div id="filter_1_123" class="filter_1_123">Some text</div> should show and other DIV should get hidden.

是否可以通过JavaScript做到这一点。

1 个答案:

答案 0 :(得分:2)

您可以将querySelectorAll与通配符div[id^='filter_1']一起使用,以filter_1开头的过滤器div ID

var filter = document.querySelectorAll("div[id^='filter_1']");

//var filter = document.querySelectorAll("div[id^='filter_1']");
function filterValue(value){
var all = document.querySelectorAll("div[id^='filter_']");

all.forEach(c=>c.removeAttribute("class","hide"));

var filter = document.querySelectorAll("div:not([id^='filter_" + value + "']");
filter.forEach(c=>c.setAttribute("class","hide"));
}
//console.log(filter.length);
//console.log(filter);
.hide{
display:none;
}
<button onclick="filterValue(1)">1</button>
<button onclick="filterValue(2)">2</button>
<button onclick="filterValue(3)">3</button>
<div id="filter_1_124" class="filter_1_124">Some text 1</div>

 <div id="filter_2_223" class="filter_2_223">Some text 2</div>

 <div id="filter_3_323" class="filter_3_323">Some text 3</div>