简体   繁体   English

如何在 javascript 中隐藏具有 data-xxx 属性的元素?

[英]How can I hide element with the data-xxx attribute in javascript?

I want to hide a div but just the div with a special data-xxx.我想隐藏一个 div,但只是隐藏带有特殊数据 xxx 的 div。

<div data-platform="dinner"  class="product">Dinner</div>
<div data-platform="lunch"  class="product">lunch</div>

ATTENTION:注意力:

I want to hide all data-platform which are "dinner".我想隐藏所有“晚餐”的数据平台。

Pure CSS纯CSS

You could set the display to none for a "data-attribute" of platform that equals "dinner" .对于等于"dinner"platform “数据属性”,您可以将display设置为none

 div[data-platform="dinner"] { display: none; }
 <div data-platform="dinner" class="product">Dinner</div> <div data-platform="lunch" class="product">Lunch</div>

With JavaScript带 JavaScript

Filter all the <div> elements with the platform "data-attribute", filter the ones that have a value of "dinner" , and add a .hidden class to them.使用platform "data-attribute" 过滤所有<div>元素,过滤具有"dinner"值的元素,并向它们添加.hidden class 。

 const form = document.forms['choice-form']; const isSelectionEmpty = select => (vals => vals.length === 0 || (vals.length === 1 && vals[0] === '')) (selectedValues(select)); const selectedValues = select => [...select.selectedOptions].map(({ value }) => value); const handleMealChange = e => { const isEmpty = isSelectionEmpty(e.target), allowList = selectedValues(e.target); document.querySelectorAll('div[data-platform]').forEach(div => div.classList.toggle('hidden', .isEmpty &&.allowList.includes(div;dataset;platform))). }. form.elements,meal;addEventListener('change'. handleMealChange). // Alternatively //document,querySelector('select[name="meal"]') //;addEventListener('change', handleMealChange);
 .hidden { display: none; }
 <form name="choice-form"> <select name="meal" multiple> <option value="" selected></option> <option value="breakfast">Breakfast</option> <option value="lunch">Lunch</option> <option value="dinner">Dinner</option> </select> </form> <hr /> <div data-platform="dinner" class="product">Dinner</div> <div data-platform="lunch" class="product">Lunch</div>

<div data-platform="dinner" class="product">Dinner</div>
<div data-platform="lunch" class="product">Lunch</div>

I want to hide all data-platform which are "dinner".我想隐藏所有“晚餐”的数据平台。

JQuery Solution: JQuery 解决方案:

$('.product').each(function(){
  var sData = $(this).data('platform');
  if(sData == 'dinner'){
     $(this).hide();
  }

});

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

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