jQuery检查href是否未定义

jQuery检查href是否未定义,jquery,Jquery,我想检查锚定标记是否没有href值,即使标记中存在href,然后向用户显示消息。例如 HTML: 注意-我无法更改此锚定标记的定义方式,因此我无法添加href=”,html由wordpress填充,我不想更改它 jQuery: $('a').click(function (e) { if ($(this).attr('href') == '') { alert('We do not have more info on this'); e.prevent

我想检查锚定标记是否没有href值,即使标记中存在href,然后向用户显示消息。例如

HTML:

注意-我无法更改此锚定标记的定义方式,因此我无法添加href=”,html由wordpress填充,我不想更改它

jQuery:

$('a').click(function (e) {
    if ($(this).attr('href') == '') { 
        alert('We do not have more info on this');
        e.preventDefault();
    }
})
但是,上述代码仅在href定义如下时有效:

<a href="" ></a>

谢谢

您可以将其用作选择器:

$('a:not([href]), a[href=""]').click(function (e) {
    alert('We do not have more info on this');
    e.preventDefault();
})

您可以将其用作选择器:

$('a:not([href]), a[href=""]').click(function (e) {
    alert('We do not have more info on this');
    e.preventDefault();
})

未定义的
和空字符串都是错误的,因此您所要做的就是直接检查属性,而不是专门检查空字符串

$('a').click(function (e) {
    if (! $(this).attr('href') ) {
        alert('We do not have more info on this');
        e.preventDefault();
    }
});

未定义的
和空字符串都是错误的,因此您所要做的就是直接检查属性,而不是专门检查空字符串

$('a').click(function (e) {
    if (! $(this).attr('href') ) {
        alert('We do not have more info on this');
        e.preventDefault();
    }
});

您可以对照
取消定义
修剪
值进行检查,并与
'
进行比较,尝试以下操作:

$('a').click(function (e) {
    var href = $(this).attr('href');
    if (href === undefined || $.trim(href) === '') {
        alert('We do not have more info on this');
        e.preventDefault();
    }
});

您可以对照
取消定义
修剪
值进行检查,并与
'
进行比较,尝试以下操作:

$('a').click(function (e) {
    var href = $(this).attr('href');
    if (href === undefined || $.trim(href) === '') {
        alert('We do not have more info on this');
        e.preventDefault();
    }
});

这很有效,谢谢。但是,为什么所有未定义href的锚标记都会弹出警报框?不是e.preventDefault()吗;假设将警报仅限于当前元素?不,preventDefault阻止默认操作,即来自锚的导航,它不会阻止未单击HREF的锚。问题是我没有单击其他元素。当我单击一个没有href的元素时,会为DOM中没有定义href的所有其他元素生成警报…我如何防止这种情况发生?谢谢。但是,为什么所有未定义href的锚标记都会弹出警报框?不是e.preventDefault()吗;假设将警报仅限于当前元素?不,preventDefault阻止默认操作,即来自锚的导航,它不会阻止未单击HREF的锚。问题是我没有单击其他元素。当我单击一个没有href的元素时,会为DOM中没有定义href的所有其他元素生成警报…我如何防止这种情况?