如何在没有 id 的 span 上触发点击事件?拒绝触发的相关跨度是 ID 等于“”的跨度。当我单击浏览器上的后退或前进按钮时,它不会执行任何操作,而所有其他按钮都会触发加载适当内容的单击事件。
<span id=""></span>
<span id="last_part_match"></span>
这就是我想要做的,但它不起作用并且破坏了代码。我的原始代码只是在 last_part ID 上触发了触发器,但这也不起作用,因为 id = ""。
window.addEventListener("popstate", function() {
var url = $(location).attr('href');
var parts = url.split("/");
var last_part = parts[parts.length-1];
if((".dashboard_post_nav span").attr('id') == last_part) {
$("#" + last_part).trigger("click");
} else {
$(".dashboard_post_nav span:first-of-type").trigger("click");
}
});
这是执行历史推送的代码,以防需要。 dash_switch 只是在点击事件中正确加载正确内容的选择器。
if(!e.isTrigger) {
if(history.pushState) {
if(dash_switch == '') {
history.pushState(null, null, '/');
} else {
history.pushState(null, null, '/' + dash_url + '/' + dash_switch + '');
}
} else {
if(dash_switch == '') {
location.hash = '/';
} else {
location.hash = '/' + dash_url + '/' + dash_switch + '';
}
}
}
最佳答案
不使用 attr()
,而是使用 id 作为选择器并检查结果的长度
if( $('#' + last_part).length ) {
关于javascript - 在 ID 等于 URL 最后一部分的 Span 上触发单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44222416/