【问题标题】:JQuery calling bind() logic twice, only on reloadJQuery 调用 bind() 逻辑两次,仅在重新加载时
【发布时间】:2011-08-28 00:50:48
【问题描述】:

我有以下代码:

$(document).ready(function () {
      $("#Titles .item a").each(function (index, domEle) {
        // 1)
      $(this).ttip($.extend(true, {}, ttip_opts, {
                content: {
                    text: $(this).attr('title'),
                    title: {
                        text: "SomeText"
                    }
                }
            }));
       // 2)
            $(this)
                .bind("click", function (event) {
                    alert(this);
                })
                .attr('title', '');
        });
});

当我单击页面上的“重新加载”并单击链接时,警报语句会显示两次。在随后的点击中,它会出现一次。

当我注释掉语句#1时,它每次只出现一次。

这里发生了什么?如何让警报语句每次显示一次?我正在循环的元素中只有一个锚元素。

更新

即使我删除了对 click 事件的绑定,我的方法(现在从另一个脚本调用)仍然会得到两次点击。所以每个函数肯定只是在重新加载时执行 click() 方法中的逻辑。

仍在试图弄清楚如何确定它是否在重新加载时被调用,所以我至少忽略了我不想运行两次的逻辑。

【问题讨论】:

  • 你忘了把你的 "$(document).ready(function () {" 结束标签吗?
  • 是.. 验证结束标记在脚本中。

标签: jquery click bind


【解决方案1】:

我认为ttip 插件正在触发我认为不需要的元素上的click 事件。你可以试试这个停止事件传播。

$(document).ready(function () {
      $("#Titles .item a").each(function (index, domEle) {
            // 2)
            $(this)
                .bind("click", function (event) {
                    alert(this);
                    return false;
            }).attr('title', '');

        // 1)
        $(this).ttip($.extend(true, {}, ttip_opts, {
                content: {
                    text: $(this).attr('title'),
                    title: {
                        text: "SomeText"
                    }
                }
        }));
    });
});

【讨论】:

  • 这个建议不太奏效。更改顺序会导致 ttip 的对象引用无效。
猜你喜欢
  • 2020-01-19
  • 2017-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多