2010-10-10 84 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

相關問題