检查是否存在没有值的数据属性

Check if data attribute exists without a value

我的目标是将一些 jQuery 添加到一个项目中,该项目将检查元素是否具有 data-attribute 而没有值。例如,使用 video 标签,您可以只添加 autoplay 而没有值,它将自动播放。我正在尝试做同样的事情,想知道是否有可能。这是我尝试过的方法,但目前返回错误:

$(function() {
  $('div').click(function() {
    if ($(this).attr('data-specs')) {
      console.log('has specs');
    } else {
      console.log('no specs');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-specs>Specs</div>

你现在得到的是一个空值,所以你可以检查它

if (typeof $(this).attr('data-specs') !== "undefined") {

if ($(this).attr('data-specs') !== "") {

$(function() {
  $('div').click(function() {
    if (typeof $(this).attr('data-specs') !== "undefined" || $(this).attr('data-specs') === "") {
      console.log('has specs');
    } else {
      console.log('no specs');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-specs>Specs</div>

<div data-no-specs>No specs</div>

您可以使用 this.hasAttribute('data-specs')

$(function() {
  $('div').click(function() {
    if (this.hasAttribute('data-specs')) {
      console.log('has specs');
    } else {
      console.log('no specs');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-specs>Specs</div>

通过jQuery您可以使用.is(selector) method.

因此,如果您将选择器设置为属性一,则可以进行检查

$(function() {
  $('div').click(function() {
    if ($(this).is('[data-specs]')) {
      console.log('has specs');
    } else {
      console.log('no specs');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-specs>Specs</div>

我想这就是你想要的:

$(function() {
  $('div[data-specs=""]').click(function(){
    console.log('has atrribute, no value');
  });
  $('div[data-specs][data-specs!=""]').click(function(){
    console.log('has atrribute, has value');
  });
  $('div[data-specs]').click(function(){
    console.log('has atrribute regardless of value');
  });
  $('div:not([data-specs])').click(function(){
    console.log('no atrribute');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-specs>Has atrribute, no value</div>
<div data-specs="some-specs">Has atrribute, has value</div>
<div>No atrribute</div>

点击检查的缩写形式:

$(function() {
  $('div').click(function(){
    if($(this).is('div[data-specs=""]')) console.log('has atrribute, no value');
    if($(this).is('div[data-specs][data-specs!=""]')) console.log('has atrribute, has value');
    if($(this).is('div[data-specs]')) console.log('has atrribute regardless of value');
    if($(this).is('div:not([data-specs])')) console.log('no atrribute');
    console.log("----");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-specs>Has atrribute, no value</div>
<div data-specs="some-specs">Has atrribute, has value</div>
<div>No atrribute</div>