Bootstrap 'shown.bs.tab' 事件未在以编程方式显示选项卡时触发(使用选项卡('show'))

Bootstrap 'shown.bs.tab' event not firing on programmatically showing the tab (using tab('show'))

这是我的 html:

<div class="profile_nav_tabs" id="profile_nav_tabs">
  <ul class="profile-tabs">
    <li>
      <a data-toggle="tab" href="#tab1">Tab 1</a>
    </li>
    <li>
      <a data-toggle="tab" href="#tab2">Tab 2</a>
    </li>
    <li>
      <a data-toggle="tab" href="#tab3">Tab 3</a>
    </li>
  </ul>
</div>


<div class="tab-content">
   <div class="tab-pane" id="tab1">Tab1</div>
   <div class="tab-pane" id="tab2">Tab2</div>
   <div class="tab-pane" id="tab3">Tab3</div>
</div>

这是我的 Javascript:

(function(){
  var hash = window.location.hash;
  if(hash){
    $("#profile_nav_tabs " + "a[href=" + hash + "]").tab('show');
  }

  $('#profile_nav_tabs a').on('shown.bs.tab', function(event){
    window.location.hash = event.target.hash;
    alert("hello");
    // some ajax call
  })
})();

现在,如果我刷新页面,url 变为 local.dev/users/profile/#tab1tab1 内容会显示,但 shown.bs.tab 事件不会触发。也就是说,既不显示警报也不进行 ajax 调用。

只有当我物理点击<a data-toggle="tab" href="#tab1">时才会触发该事件。

我希望 url 在每次选项卡更改时更新,我还希望在页面加载时显示该选项卡后进行回调。

shown.bs.tab 事件是否不会在以编程方式显示选项卡时触发?

要让您的代码达到 运行 需要做两件事:

  1. 插入 jQuery 的属性等于选择器时,正确引用或转义 hash(由于 # 字符)。见 jQuery Selectors, Category: Attribute:

    Attribute values in selector expressions must follow the rules for W3C CSS selectors; in general, that means anything other than a valid identifier should be surrounded by quotation marks.

    • double quotes inside single quotes: $('a[rel="nofollow self"]')
    • single quotes inside double quotes: $("a[rel='nofollow self']")
    • escaped single quotes inside single quotes: $('a[rel=\'nofollow self\']')
    • escaped double quotes inside double quotes: $("a[rel=\"nofollow self\"]")

    The variation you choose is generally a matter of style or convenience.

    在上面的引用中链接,W3C 在 CSS 中的 "valid identifiers" 上有以下说法:

    In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B WF".

    # 字符是代码点 U+0023,超出了有效标识符中允许的字符范围。

  2. 执行前添加shown.bs.tab事件处理程序$.tab('show')

因此将您的脚本更改为以下内容:

(function(){
  $('#profile_nav_tabs a').on('shown.bs.tab', function(event){
    window.location.hash = event.target.hash;
    alert("hello");
    // some ajax call
  });

  var hash = window.location.hash;
  if(hash){
    $("#profile_nav_tabs " + 'a[href="' + hash + '"]').tab('show');
  }
})();

这必须放在 DOM 中您的 HTML 片段之后,但我认为情况已经如此。

另请注意,您在绑定事件处理程序后缺少分号。