jQuery 属性存在与否

Ali*_*ice 1 javascript jquery

如何在 jQuery 中查找所选项目是否存在某个属性?

例如,选定的元素 jQuery('.button'),现在可以有一个属性 'xyz'。我如何知道它是否具有该功能?

brk*_*brk 7

您可以使用hasAttribute方法:

// Attach the event to the button
$('button').on('click', function() {
  // This will refer the element from where event has originated
  if (this.hasAttribute("style")) {
    alert('yes')
  } else {
    alert('no')
  }

})
Run Code Online (Sandbox Code Playgroud)

如果要使用jQuery库,可以直接使用条件attr中的方法if。

if($('#yourElement').attr('someProp')){}
Run Code Online (Sandbox Code Playgroud)

或者,您也可以使用 jQuery is选择器:

if ($(this).is('[style]')) {// rest of the code}
Run Code Online (Sandbox Code Playgroud)

演示版