当不合适的href时,jQuery返回undefined的href [英] jquery returns undefined for href when not a proper href
问题描述
我有以下代码:
function DelayTarget(e) {
var t = $(e.target);
var href = ((t.is("a") ? t : t.find("a")).first()).attr("href");
if (typeof href !== typeof undefined && href !== false) {
// Do something
}
}
当我对此链接进行测试时,它可以正常工作:
When I test with this link it works correctly:
href="/contact"
当我对此链接进行测试时,它不起作用:
When I test with this link it doesn't work:
href="javascript:history.back()"
第一个测试正确识别href值,但第二个返回未定义. jQuery知道有效和无效网址之间的区别似乎很奇怪.
The first test correctly identifies the href value but the second returns undefined. It seems odd that jquery would know the difference between a valid and invalid url.
有人知道我要去哪里吗?
Anyone know where I'm going wrong?
更新-这是导致问题的原因:
UPDATE - this is what is causing the issue:
<a href="javascript:history.back()"><i class="material-icons">arrow_back</i></a>
推荐答案
来自 W3C :
target
属性获取最初发生事件的元素,与currentTarget
属性相反,currentTarget
属性始终引用事件侦听器触发事件的元素.
The
target
property gets the element on which the event originally occurred, opposed to thecurrentTarget
property, which always refers to the element whose event listener triggered the event.
因此失败,因为e.target
返回被单击的最里面的DOM元素,在这种情况下为<i>
.与链接之一包含JavaScript的事实无关.要解决此问题,只需将e.target
更改为e.currentTarget
.
So it fails because e.target
returns the innermost DOM element clicked, in this case the <i>
. It has nothing to do with the fact that one of the links contains JavaScript. To solve the problem, just change e.target
to e.currentTarget
.
或者,使用this
代替:
$('a').click(function() {
DelayTarget(this);
});
function DelayTarget(o) {
var t = $(o);
var href = (t.is("a") ? t : t.find("a")).first().attr("href");
if (typeof href !== typeof undefined && href !== false) {
// Do something
}
}
这篇关于当不合适的href时,jQuery返回undefined的href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!