2010-10-10 85 views
0

我有一个元素可以抓取输入的内容并进行交换,然后我希望用户能够点击输入(正常输入文本),但是如果他们点击其他任何地方将其交换回文本。jQuery的行为并不像预期的那样引用点击

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

$(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()); 
    }); 
    }); 
}); 

回答

2

它会提醒,即使第一次是第一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

+0

在第二个版本中,我在chrome中看到错误“Uncaught SyntaxError:Unexpected token ILLEGAL”,查找它并且似乎与命名错误相关,但是我看不到会导致此错误? – 2010-10-10 11:57:55

+0

@Pez - 你是从jsfiddle复制/粘贴的吗?有时候,看起来像一个空间的奇怪角色会在那里滑动,尝试删除所有空格并查看它是否修复它(空格/奇怪的字符最终可能是*)。 – 2010-10-10 11:59:04

+0

不,我使用在这里发布的代码在stackoverflow ...嗯......我会玩,看看我是否可以修复它! – 2010-10-10 12:06:38

相关问题