无法调用 null 的方法 'append'



使用jQuery 1.6.0问题时遇到了这个奇怪的问题。如果用户在文本框中键入的字符超过3个,我将尝试将一些内容附加到div中。

这是我的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="Name"。

如果我alert($('#Name'));,我得到null,但如果我alert($('Name')),我得到[object HTMLDivElement],但它仍然不允许我追加。

使用jQuery 1.6.0

如果有语法错误,请尝试此方法(选择器不带#)。。。请使用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>");
    }
  }
});

我已经切换到使用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");
    }
  }
});

最新更新