我有以下代码:
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
}
}
当我使用此链接进行测试时,它可以正常工作:
href="/contact"
当我使用此链接进行测试时,它不起作用:
href="javascript:history.back()"
第一个测试正确识别了 href 值,但第二个测试返回未定义。 jquery 知道有效和无效 url 之间的区别,这似乎很奇怪。
有人知道我哪里出错了吗?
更新 - 这就是导致问题的原因:
<a href="javascript:history.back()"><i class="material-icons">arrow_back</i></a>
最佳答案
来自W3C :
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
.
或者,使用 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
}
}
关于javascript - 当不是正确的 href 时,jquery 返回未定义的 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32505769/