【问题标题】:Click Event Listner on Hashchange page using jQuery使用 jQuery 在 Hashchange 页面上单击事件侦听器
【发布时间】:2016-12-05 18:23:22
【问题描述】:

对于哈希更改页面的点击事件处理程序有什么特定的方法吗?例如,假设我有一个页面​abc.com​。单击特定选项卡会为我们提供 abc.com#/tab1,这是一个散列页面。在散列页面上,我想在 Save​ 按钮上添加点击事件。

我的实现假设元素都是 body 的子节点,因此使用事件委托。但是,同样不能按预期工作。

window.addEventListener("hashchange", function () {
    console.log(window.location.hash);
    $( "body" ).on( "click", "button", function( event ) {
      if (window.location.hash === "#/tab1")
        console.log("testing success");
    });
});

【问题讨论】:

  • 嘿,恭喜您提出第一个 Stackoverflow 问题 :) 欢迎!我做了一些编辑。大多数是对文本的微不足道的间距编辑,但我也将您的代码块更改为以 4 个空格开头的格式。当你想有一些内联代码时通常使用反引号,比如this for example

标签: javascript jquery


【解决方案1】:

正如answer of this post 中提到的,您可以使用 jQuery 方法来实现这一点:

$(window).on('hashchange', function() {

  console.log(window.location.hash);

    saveButton = $('#saveBtn:not(.bound)');
    if (saveButton != undefined) {
        saveButton.addClass('bound').click(function(){
            if (window.location.hash == '#/tab1') {
                console.log('testing success!');
            }
        });
    }
});

检查.bound 类可确保单击事件仅绑定到保存按钮一次。 (Source here)

【讨论】:

  • 感谢您的回复。它的部分工作。问题是,最初当我单击 Save 按钮时,它不起作用。但是,当我再次访问该页面时,它正在工作。我当前的实现使用 .ready() 来检查 DOM 内容是否已加载,但仍然无法正常工作。代码在下一条评论中提供。
  • $(document).ready(function() { button = $("div.class button"); console.log(button); console.log($("div.class button").length); if (button !== undefined) { $("div.class button").click(function() { if (window.location.hash == '#/tab-1') { console.log('testing success new 2!'); } }); } });
  • div.class button 指的是
    内的
  • 代替“div.class button”,你可以尝试只使用“button”,或者具体来说,你的Save按钮的id?
猜你喜欢
相关资源
最近更新 更多
热门标签