简体   繁体   中英

How to determine if an element has NO data-attr

I have a sort of a niche case here.

So I'm building out a sidebar tool to utilize for quick note-taking, and I'm running into a problem without setting hundreds of data-attr s.

Currently, I have a dropdown menu that displays content that contains a specific data-attr based on the selection and hides the rest. The problem I'm encountering is I also want it to display all items that do not contain any data-attr s.

Is there a simple way to check if an item has no HTML defined data sets?

HTML:

<select id="ouSelect">
  <option></option>
  <option data-ou="aiv">AIV ***</option>    
  <option data-ou="appstore">Appstore ***</option>
  <option data-ou="firetv">Fire TV ***</option>
  <option data-ou="kindle">Kindle ***</option>
</select>

<ul id="stuffs">
  <li data-kindle="true">Kindle</li>
  <li>Generic</li>
  <li data-aiv="true">AIV</li>
  <li>Generic</li>
  <li data-firetv="true">FireTV</li>
  <li>Generic</li>
  <li data-appstore="true">Appstore</li>
  <li>Generic</li>
</ul>

jQuery:

$(function(){
  var ou = "";
  $('#ouSelect').change(function() {
    ou = $('#ouSelect option:selected').data('ou');
    ouSelected(ou);
  });
  function ouSelected(which){
    $('li').each(function(){
      if($(this).data(which) === undefined){
        $(this).hide();
      } else {
        $(this).show();
      }
    })
  }
});

CodePen: http://codepen.io/anon/pen/GyqoK

As you can see, all of the generic sets disappear when an option is selected. Ideally I'd want the items with data-kindle to display as well as items with no data-attr s at all.

Any ideas how to accomplish this? Any help is appreciated!

将您的支票更改为此:

if($(this).data(which) === undefined && Object.keys($(this).data()).length > 0)

Given support for the dataset property, it's as easy as:

Object.keys(element.dataset).length === 0

That's not really appropriate, though. data-* attributes aren't meant to interfere with each other, and they shouldn't have dynamic names. How about identifying categories in a simpler way?

<li data-category="appstore">Appstore</li>

(Not given support for the dataset property, you can use

function hasDataAttributes(element) {
    for (var i = 0; i < element.attributes.length; i++) {
        var name = element.attributes[i].name;

        if (name.substring(0, 5) === 'data-') {
            return true;
        }
    }

    return false;
}

.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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