问题描述
我有以下代码:
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 :
因此失败,因为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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!