每次单击jQuery函数都会被调用两次 [英] jQuery function gets called twice for each click

查看:136
本文介绍了每次单击jQuery函数都会被调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置:

当单击table_1中的一行时,我已经编写了一个jQuery函数来更新table_2的表单元格.这是我写的:

I have written a jQuery function to update table cells of table_2, when a row in table_1 is clicked. Here is what I have written:

    <script type="text/javascript">
        $("tr").live('click',function() {
            var host = $(this);
            alert('A row in table 1 is clicked!');

            var count = host.find("td").eq(2).text();
            $("#myTable_2 tr:eq(0) td:eq(1)").text(count);
            $("#myTable_2 tr:eq(1) td:eq(1)").text(5);
        });
    </script>

问题:

当我使用FireBug逐步执行此功能时,可以看到myTable_2中的单元格数据正在更改.但是,每次单击都会执行两次该功能.我可以看到警报框每次点击都会出现两次.

When I step-through this function using FireBug, I can see the cell data in myTable_2 is being changed. BUT, for every click, the function is executed twice. I can see the alert box appearing twice for each click.

有人可以告诉我为什么会这样吗?以及如何避免这种情况?

Can somebody tell me why does this happen? And how to avoid this?

推荐答案

以下任意一项:

  1. 单击的行在另一行内(单击了两行). (示例)
  2. 您显示的代码执行了两次(示例).
  1. The clicked row is inside another row (two rows are clicked). (example)
  2. The code you've shown is executed twice (example).

要解决此问题,请使选择器更具体.如果您使用的是jQuery 1.7+,请使用 .on 而不是live:http://jsfiddle.net/6UmpY/3/

To solve this, make your selector more specific. If you're using jQuery 1.7+, use .on instead of live: http://jsfiddle.net/6UmpY/3/

$(document).on("click", "#myTable_1 > tbody > tr", function() {
    // This selector will only match direct rows of the myTable_1 table

注意:使用.on代替live不能解决问题.
使用更具体的选择器 did 可以解决此问题.
如果您喜欢live,则以下内容也可以使用: http://jsfiddle.net/6UmpY/4/

Note: Using .on instead of live did not solve the problem.
Using a more specific selector did fix the issue.
If you love live, the following would also work: http://jsfiddle.net/6UmpY/4/

$("#myTable_1 > tbody > tr").live("click", function() {

这篇关于每次单击jQuery函数都会被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆