用户离开指定目标时的jQuery目标和单击绑定

时间:2014-04-02 17:10:02

标签: jquery html forms

我正在创建一个可以从网格布局中编辑的表。

目标:如果用户双击可编辑的行/列,则可以操纵input。然后当他们点击此对象外部时,它会触发$.ajax事件,保存他们的更改。

我在这里有一个问题的工作示例:http://jsfiddle.net/Q3enw/5/ 您可以看到,虽然它可以进行编辑,但只要您点击任何地方,它就表示您已在容器外点击。

jQuery代码

$(".canEdit").dblclick(function () {
   $(this).find("input").attr("readonly", false).css("background", "white");
   var container = $(this); //set area to see when clicked outside
   $(document).click(function (e) {
     if (!container.is(e.target)) {
       alert("clicked outside container");
       //handle ajax submission since they left
      } else {
       console.log("still inside container");
       //do nothing, allow them to continue editing
      }
   });
});

问题:有没有更好的方法来处理用户在之前双击区域外点击的时间?我认为绑定一个e.stopPropogation();就足够了,但它不能长时间停止该功能以双击一个新行。也许我不应该使用$(document).click,因为这会将文档绑定到单个事件?

如果需要进一步的信息,请告诉我。提前谢谢!

2 个答案:

答案 0 :(得分:1)

使用if (container.find(e.target).length<=0) // which will check whether container contains clicked element.

而不是

if (!container.is(e.target)) //which will check container (i.e., td in your case) is equal to e.target which will be input/child elements.

试试这个:

$(".canEdit").dblclick(function () {
    $(this).find("input").attr("readonly",false).css("background","white");
    var container = $(this); //set area to see when clicked outside
    $(document).click(function (e) {
        if (container.find(e.target).length<=0) {
            alert("clicked outside container");
            //handle ajax submission since they left
        } else {
            console.log("still inside container");
            //do nothing, allow them to continue editing
        }
    });
});

<强> DEMO

答案 1 :(得分:1)

您可以使用模糊功能吗?像这样:

$(".canEdit").dblclick(function () {
    $(this).find("input").attr("readonly",false).css("background","white")
    .blur(function () {
        alert(1);
    });
}); 

Fiddle

您也可以将css分开并使用addClass()

$(".canEdit").dblclick(function () {
    $(this)
    .find("input")
    .attr("readonly",false)
    .addClass('editable')
    .blur(function () {
        alert(1);
    });
});

fiddle