2012-03-08 84 views
0

使用jQuery 1.6.0問題引發了這個奇怪的問題。如果用戶在文本框中輸入了3個以上的字符,我試圖將一些內容附加到div上。無法調用null的方法'append'

這裏是我的JS

$('#Form_pickForm_Name').keyup(function() { 
    var searched = $('Form_pickForm_Name').value; 
    if (searched.length > 2) { 
    // Add the name_suggestions if doesn't exit 
    if ($("name_suggestions").length < 1){ 
     $('#Name').append("<div id='name_suggestions'>Foo!</div>"); 
    } 
    } 
}); 

這是相關的HTML

<div id="Name" class="field text "> 
    <label class="left" for="Form_pickForm_Name">Your Full Name</label> 
    <div class="middleColumn"> 
     <input type="text" class="text" id="Form_pickForm_Name" name="Name" value="" /> 
    </div> 
</div> 

我檢查了頁面,並沒有其他的id = 「名稱」 就可以了。

如果我alert($('#Name'));我得到空,但如果我alert($('Name'))我得到[對象HTMLDivElement],但它仍然不會讓我追加。

使用jQuery 1.6.0

+0

因爲缺少一些「#」。 – benck 2012-03-08 09:49:23

回答

1

你有語法錯誤,試試這個方法(選擇無#)...請使用VAL()方法,而不是價值:

$('#Form_pickForm_Name').keyup(function() { 
    var searched = $('#Form_pickForm_Name').val(); 
    if (searched.length > 2) { 
    // Add the name_suggestions if doesn't exit 
    if ($("#name_suggestions").length < 1){ 
    $('#Name').append("<div id='name_suggestions'>Foo!</div>"); 
    } 
    } 
}); 
+0

謝謝,#是問題,但我的關鍵是val(),因爲我正在使用它來測試,並且值將爲空,所以我認爲這是選擇器! – Wizzard 2012-03-08 09:57:04

1

我已經切換到使用appendTo,我認爲你需要的$對象來創建一個元素。

此外,也有一些語法錯誤(缺少哈希對開的ID)

$('#Form_pickForm_Name').keyup(function() { 
    var searched = $('#Form_pickForm_Name').value; 
    if (searched.length > 2) { 
    // Add the name_suggestions if doesn't exit 
    if ($("#name_suggestions").length < 1){ 
     $("<div id='name_suggestions'>Foo!</div>").appendTo("#Name"); 

    } 
    } 
}); 
相關問題