jQuery 模式浏览​​器安全吗:"attr('foo') || 'default'"?

Is this jQuery pattern browser-safe: "attr('foo') || 'default'"?

这似乎是一种从数据属性读取值或使用默认值(如果不存在)的巧妙方法:

var confirmMessage = resourceDiv.attr("data-confirm-delete-text") || "Delete this resource?";

它依赖于 undefined(如果属性不存在则返回)是错误的。这是浏览器安全的解决方案吗?如果不是,有什么更好的方法?

是的,它是浏览器安全的。小心将它用于有效时为假的值,例如 0false。另请注意,您会发现一些人不喜欢使用该构造,但这主要是为了代码可读性问题,而不是浏览器支持。

备选方案是 if 语句:

var confirmMessage = resourceDiv.attr("data-confirm-delete-text");
if (!confirmMessage)
  confirmMessage = "Delete this resource?";

或者三元:

var confirmMessage = resourceDiv.attr("data-confirm-delete-text") ? resourceDiv.attr("data-confirm-delete-text") : 'Delete this resource?';

如您所见,它们更加冗长,并且在三元的情况下,可能包含一些冗余。