2011-04-11 136 views
1

我有一個表單輸入,其執行每一個鍵被按下的時間KEYUP功能,我得到的螢火一個警告,說:如何避免這種重複的鍵盤錯誤/警告?

The 'charCode' property of a keyup event should not be used. The value is meaningless. 

我這個翻譯爲「標籤已經隱然你keyup事件什麼都不做「

事情是......我只需要這個keyup函數來運行一次。

很簡單,功能是一個帶有字段提示的標籤,例如「輸入您的電子郵件」,將鼠標懸停在文本輸入上。打字時,標籤消失。

問題是,我的代碼試圖每次推送密鑰時都繼續隱藏此標籤。

我使用的HTML代碼:

<label for='inp_email'>enter your email</label> 
<input id="inp_email" name="inp[email]" class="inp" /> 

的jQuery是

$(document).ready(function(){ 

    $('.inp').keyup(function(){ 

     $(this).prev('label').fadeOut('fast'); 

    }); 

}); 

因此,我認爲它需要做這樣的檢查:

$('.inp').keyup(function(){ 

    $(this).prev('label:visible').fadeOut('fast'); 

}); 

(注: ':visible'in the selector。)

這不起作用。

而且我也試過:

$('.inp').keyup(function(){ 

    $(this).prev('label').is(':visible').fadeOut('fast'); 

}); 

但是error'd,所以我似乎不明白。是功能很好呢。

任何想法?

+0

看你的代碼:我不知道方括號中的ID是很好的做法,甚至無效。您還沒有爲輸入字段指定類型?你應該嘗試追加新的類到你的元素,然後添加/刪除這些,當你想隱藏它們。例如給它一個隱藏的類,然後根據這個進行搜索和修改。 – timothyclifford 2011-04-11 22:36:53

+0

謝謝蒂莫西。在我急匆匆的時候,我在上面寫錯了代碼。我已經糾正它 - 再次感謝。 – willdanceforfun 2011-04-11 22:38:58

回答

1

首先做一個檢查,如:

 if ($(this).prev('label').is(":visible")) 
    { 
     $(this).prev('label').fadeOut('fast'); 
    } 

如前所述在JQuery API中,「與其他過濾方法不同,.is()不會創建新的jQuery對象。」所以你不能鏈接它。

這是一個帶有工作版本的jsfiddle

+0

謝謝,我剛剛嘗試過,仍然得到相同的警告 – willdanceforfun 2011-04-11 22:40:51

+0

感謝您對.is()進行鏈接說明,這解釋了很多。 – willdanceforfun 2011-04-11 22:42:44

+0

@KeenLearner:儘管代碼現在可以工作,但你只能得到一次警告嗎? – Town 2011-04-11 22:45:46

0

參見:The 'charCode' property of a keyup event should not be used. The value is meaningless

基本上,它看起來像你需要等到DOM準備就緒,與

$(document).ready(function(){ 

    // stuff here 

}); 
+0

我將編輯我的文章,因爲我的函數在$(document).ready(function(){}中已經... – willdanceforfun 2011-04-11 22:36:34

+1

在你鏈接的問題中,警告與該問題的OP的實際問題不相關。真正的解決方案是這樣的:[忽略](http://stackoverflow.com/questions/1823951/the-charcode-property-of-a-keyup-event-should-not-be-used-the-value-is-意思/ 1823960#1823960)。也許將來的jQuery版本會修復它。 – 2011-04-11 22:46:54

0

什麼是這樣的:

<label for="EmailInput" class="show-me">Enter your email</label> 
<input id="EmailInput" class="email-input" type="text" /> 

$(document).ready(function() { 

    $('input[type=text]').keyup(function() { 

     var idValue = $(this).attr('id'); 

     var label = $('label[for="' + idValue + '"]'); 

     if ($(label).hasClass('hidden')) 
     { 
      $(label).removeClass('hidden'); 
     } 
     else 
     { 
      $(label).addClass('hidden'); 
     } 

    }); 
}); 

可以看到它在這裏工作:http://jsfiddle.net/timothyclifford/5Y9Ws/2/

+0

乾杯蒂莫西。我檢查了這個例子,它的工作原理,但JavaScript警告仍然出現在螢火蟲控制檯。 – willdanceforfun 2011-04-11 23:22:50

+0

我沒有收到任何Firebug警告... – timothyclifford 2011-04-11 23:28:22

1

該警告是不相關的代碼無法正常工作。

這只是jQuery愚蠢。有一天jQuery會解決它。

Ignore it.

+0

感謝您的支持。我意識到它只是一個警告......我不確定它是否浪費了最終用戶的資源。 – willdanceforfun 2011-04-11 22:49:28

+0

@KeenLearner:如果他們打開了Firebug,可能是。 :) – 2011-04-11 22:49:45