【问题标题】:jQuery can't find the html elements just appenedjQuery 找不到刚刚添加的 html 元素
【发布时间】:2011-05-22 14:44:05
【问题描述】:

我有以下 html 代码:

<div id='list'>
  <ul></ul>
</div>

我有以下 jQuery 脚本:

function append_list(){
  $('ul').append('<li><input type="image" name="original" value="'+SOMEVALUE+'"></li>');
}

function find_input(){
  //some code to find the just appended input element.
}

$(document).ready(function(){
  append_list();
  console.log($('input'));
  find_input();
});

当我查看浏览器控制台时,console.log 的输出只是一个空数组“[]”,但是如果我输入 console.log($('input'));页面加载后在我的浏览器控制台中,它可以反馈正确的数据... 我对 .append() 函数做了什么坏事吗?

感谢您的帮助。

----编辑----
谢谢大家,我想在我的问题中添加一些内容。 我已经尝试过你对 setTimeout(); 的建议;但仍然找不到我附加的输入元素。 我也将console.log($('input)); 添加到function append_list(); 中也没有帮助...现在我在这里堆叠:-(

【问题讨论】:

  • 您对 append 函数的使用看起来不错。问题是console.log 在append_list() 有机会完成之前正在运行。你想在这里完成什么?
  • 你好@Bryan,我想是在 append_list();完成后,我将得到 $('input[name="original"]') 的数组,然后我可以调用例如 $('input[name="original"]')[1].value 来获取供以后使用的价值。

标签: javascript jquery append


【解决方案1】:

你应该设置一个回调函数。

查看:http://jsfiddle.net/bryandowning/4mS9L/

function append_list(someval, callback){

    //save a reference to the element you are appending
    var $element = $('<li><input type="text" name="original" value="'+someval+'"></li>');

    //append it to the list
    $('ul').append($element);

    //if a callback function was provided, execute it.        
    if(arguments.length === 2){
        //pass the callback function the saved reference to the appended element
        callback($element);   
    }
}

//this is the callback function
function find_input(item){
    var $input = item.find("input");

    $input.after("The value of the input element is: " + $input.val());
}

$(document).ready(function(){
    //example with the callback provided
    append_list("First Element", find_input);

    //example without the callback provided
    append_list("Second Element");

});

【讨论】:

    【解决方案2】:

    我觉得奇怪的是 append_list() 没有在 console.log 之前完成......这是一些人的建议,但我很难找到另一个原因。

    但是,您可以保证引用您的输入,如下所示:

    function append_list() {
       return $('<li><input type="image" name="original" value="'+SOMEVALUE+'"></li>')
          .appendTo('ul')
          .find('input');
    }
    

    append_list() 返回的值现在直接引用您创建的输入,而不是从头开始搜索文档。

    【讨论】:

    • 这是获取对新创建对象的引用的正确方法,虽然我会返回对
    • 元素的引用而不是输入元素,然后您可以相应地使用它
  • @David - 同意,我也会返回 &lt;li&gt;,但只是为了简化问题。
  • 【解决方案3】:

    尝试给列表一个 id:

    <ul id='myul'></ul>
    

    然后

    $('#myul').append(...
    

    【讨论】:

      【解决方案4】:

      嗯,它应该会找到它...尝试让它“呼吸”...

      append_list();
      setTimeout(find_input, 1);
      

      【讨论】:

        【解决方案5】:

        看起来在 UI 更改完成之前 console.log 正在运行,这就是它没有找到添加的元素的原因。如果您使用延迟 1 毫秒的 setTimout 将强制延迟执行以下代码,直到 UI 更改完成,这应该会给出正确的结果。

        append_list();
        setTimeout(function() {
          console.log($('input'));
          find_input();
        }, 1);
        

        【讨论】:

          猜你喜欢
          相关资源
          最近更新 更多
          热门标签