将click事件绑定到td vs table [英] Binding click event to td vs table

查看:157
本文介绍了将click事件绑定到td vs table的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在HTML中构建类似于实用程序的excel。假设我的表[idmyTbl]有20行& 20列。每当用户点击td文本作为其值时,我想在td中添加文本框。

I want to build excel like utility in HTML. Suppose I've table[id "myTbl"] with 20 rows & 20 columns. I would like to add textbox inside td whenever users clicks on it with td text as its value.

假设我的表是

Suppose my table is

我有2个选项来实现这一目标工作正常]

I've 2 options to achieve this [both are working fine]

选项I

$("#myTbl").bind("click",function(e){
    var obj = e.target;
    if(obj.nodeName == "TD"){
        $(obj).html("<input type='text' value='"+$(obj).html()+"'></input>");
    }
});

选项II

$("#myTbl tr td").bind("click",function(e){
    if($("input",$(this)).length==0){
        $(this).html("<input type='text' value='"+$(this).html()+"'></input>");
    }
});

我的问题是哪个选项在性能方面更好。

My question is which option is better in terms of performance.

推荐答案

您的两个选项中的第一个将只创建一个事件处理程序,因此它会更高效。
通过事件获取目标的成本可以忽略不计。

The first of your two options will create only one event handler, so it'll be more performant. Obtaining the target via the event as you do has negligible cost.

要做'jQuery'方式,你可能想要使用 委托

To do it the 'jQuery' way, you might want to use delegate:

$("#myTbl").delegate("td", "click", function() {
  var $this = $(this);
  $this.html("<input type='text' value='"+$this.text()+"'></input>");
});

这篇关于将click事件绑定到td vs table的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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