我可以使用以下命令检查元素是否具有特定属性:
if ($('#A').attr('myattr') !== undefined) {
// attribute exists
} else {
// attribute does not exist
}
如何检查一个元素是否有任何属性?
谢谢
发布于 2010-02-11 05:00:27
下面是一个函数,用于确定匹配选择器的任何元素是否至少有一个属性:
function hasOneOrMoreAttributes(selector) {
var hasAttribute = false;
$(selector).each(function(index, element) {
if (element.attributes.length > 0) {
hasAttribute = true;
return false; // breaks out of the each once we find an attribute
}
});
return hasAttribute;
}
用法:
if (hasOneOrMoreAttributes('.someClass')) {
// Do something
}
如果你想对至少有一个属性的选定元素进行操作,那就更简单了--你可以创建一个自定义过滤器:
// Works on the latest versions of Firefox, IE, Safari, and Chrome
// But not IE 6 (for reasons I don't understand)
jQuery.expr[':'].hasAttributes = function(elem) {
return elem.attributes.length;
};
它可以像这样使用:
$(document).ready(function(){
$('li:hasAttributes').addClass('superImportant');
}
发布于 2010-02-11 04:24:26
如果您想查看元素是否具有特定属性,只需执行以下操作:
if ($('#something').is('[attribute]')) {
// ...
}
发布于 2012-08-07 11:33:19
$("selector").get(0).hasAttributes("attributes");
https://stackoverflow.com/questions/2240061
复制相似问题