我有一个元素,可以抓住其中的内容并交换为输入,然后我希望用户能够单击输入(以正常方式输入文本),但是如果他们单击其他任何地方以将其交换回文本。

但是,即使用户第一次单击页面上的任何位置,单击事件似乎也会触发。我的代码在下面,我误解了吗?

$(document).ready(function(){
   $("#thingy").css('cursor', 'pointer');
   $("#thingy").one("click", function() {
     var element = $(this);
     element.css('cursor', 'auto');
     element.css('display', 'inline-block');
     element.fadeOut(100, function(){element.html('<input type="text" size="25" value="' + element.text() + '" style="width:' + element.width() + 'px;height:' + element.height() + 'px;border:none;padding:0px;margin:0px;">')}).fadeIn(100);
     $("#thingy").click(function() {
       return false;
     });
     $(document).click(function() {
         alert("You clicked off the text-box");
         element.html(element.children('input:text').val());
     });
  });
});

最佳答案

它甚至第一次发出警报的原因是第一个click处理程序(.one()本身不是return false;.stopPropgaton(),如下所示:

$(document).ready(function(){
   $("#thingy").css('cursor', 'pointer');
   $("#thingy").one("click", function() {
     var element = $(this);
     element.css('cursor', 'auto');
     element.css('display', 'inline-block');
     element.fadeOut(100, function(){element.html('<input type="text" size="25" value="' + element.text() + '" style="width:' + element.width() + 'px;height:' + element.height() + 'px;border:none;padding:0px;margin:0px;">')}).fadeIn(100);
     $("#thingy").click(function() {
       return false;
     });
     $(document).click(function() {
         alert("You clicked off the text-box");
         element.html(element.children('input:text').val());
     });
     return false;
  });
}); ​


You can test it out here

更好的方法是改为使用blur事件,替换为:

     $("#thingy").click(function() {
       return false;
     });
     $(document).click(function() {
         alert("You clicked off the text-box");
         element.html(element.children('input:text').val());
     });
     return false;


有了这个:

     $(element).delegate("input", "blur", function() {
       element.html(element.children('input:text').val());
     });


You can try that version here

10-06 07:30
查看更多