我在 HTML 元素中使用数据属性
例子:
<div class="fruit" data-color="red">...</div>
在 jQuery 中,我使用 $(this).data("color")
获取数据属性,并将其添加到元素中具有类名。
在将数据属性添加为类之前是否需要先验证它是否存在?示例:
// $(this) is .fruit div
if ( $(this).data("color") ) {
$(this).addClass($(this).data("color")); //adds data value as class to element
}
或者 jQuery 会处理吗?我尝试在没有 if 语句的情况下运行代码,如果元素没有“颜色”数据属性,我不会收到任何错误。我猜 jQuery 只是忽略了它。
最佳答案
jQuery 会为您处理 - 事实上,它非常健壮,可以接受大多数方法参数而不会抛出任何错误。
在这种情况下,如果未找到data
属性(或没有值),它将返回undefined
。如果您随后 addClass(undefined)
jQuery 将不会对所选元素执行任何操作。
关于javascript - 是否需要检查元素是否具有属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30085964/