避免jquery select中的类型错误

Avoid type error from jquery select

本文关键字:类型 错误 jquery select 避免      更新时间:2023-09-26

我必须从jQuery选择器中获取一个属性:

var id=$("#nav-titles li.active a").attr("href").replace(/^#/,"");

如果jquery选择器js中没有项目,则会记录此错误:

TypeError: $(...).attr(...) is undefined

如何避免这个错误并存储"未定义"(或false,或null)的id变量?


我知道我可以做到:

var id=$("#nav-titles li.active a").length && $("#nav-titles li.active a").attr("href")?$("#nav-titles li.active a").attr("href").replace(/^#/,""):null;

但是,对于一个如此简单的请求,使用3个选择器真的有必要吗?

如果您不确定是否存在锚标记,这将更具可读性

 var $anchor = $('#nav-titles li.active a');
 if( $anchor.length > 0 && $anchor.attr('href')){
    id= $anchor.attr("href").replace(/^#/,"");
 }

无需检查集合的length。当.attr返回undefined值时,集合为空。以下代码段使用||运算符。当attr返回一个错误值时,会传递一个空字符串。

var id = ($("#nav-titles li.active a").attr("href") || '').replace(/^#/,"") || null;

听起来你想对你找到的每个元素都这样做:

var id=$("#nav-titles li.active a").each(function()
{
    $( this ).attr("href").replace(/^#/,"");
});