【问题标题】:Trigger Click On Span Without ID Equal To Last Part Of URL触发点击跨度没有 ID 等于 URL 的最后部分
【发布时间】:2017-05-27 23:17:12
【问题描述】:

如何在没有 id 的 span 上触发 click 事件?拒绝触发的有问题的跨度是 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 + '';
    }
  }

}

【问题讨论】:

  • 浏览器控制台会抛出什么错误?注意弹出状态if()中缺少$
  • @charlietfl 我添加了 $ 并且它停止了中断,但它每次都会触发第一个跨度,所以我不确定如何检查 id="" 与否。
  • @charlietfl 我试过检查 span attr id == '' 或 length = 0,它仍然是第一个 span。
  • 试试$("span[id='']").first()... 但我不确定它是否有效。而且我不明白它的用途......

标签: javascript jquery html5-history


【解决方案1】:

不要使用attr(),而是使用 id 作为选择器并检查结果的长度

if( $('#' + last_part).length ) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2013-03-02
    • 2011-07-29
    相关资源
    最近更新 更多