Javascript jQuery:已创建DOM的缓存引用

Javascript jQuery:已创建DOM的缓存引用,javascript,jquery,dom,Javascript,Jquery,Dom,请看以下假设代码: // create some list we work with $('body').html('<ul class="collection-list"></ul>'); // some array with string data var collection = ['foo', 'bar', 'foobar']; // here we store our jquery objects var doms = []; // for each it

请看以下假设代码:

// create some list we work with
$('body').html('<ul class="collection-list"></ul>');

// some array with string data
var collection = ['foo', 'bar', 'foobar'];

// here we store our jquery objects
var doms = [];

// for each item in the collection array we create a li
$.each(collection, function(index, value) {
    // imagine that the jquery part would return a reference/object which we push into our doms array
    doms.push($('ul.collection-list').append('<li class="item">' + value + '</li>'));
});

// we could now do different logic through our cached object
doms[2].val('new value');
doms[1].remove();
//创建一些我们使用的列表
$('body').html('
    ); //包含字符串数据的数组 变量集合=['foo','bar','foobar']; //这里我们存储jquery对象 var-doms=[]; //对于集合数组中的每个项目,我们创建一个li $.each(集合、函数(索引、值){ //假设jquery部分将返回一个引用/对象,我们将其推入doms数组 doms.push($('ul.collection list').append('
  • '+value+'
  • '); }); //我们现在可以通过缓存对象执行不同的逻辑 doms[2].val(“新值”); doms[1]。删除();

    这可能是因为这个例子没有任何逻辑意义,但请不要给我其他的选择!我只想使用所介绍的技术。这个例子就是一个例子

    您将整个
    ul
    元素存储在循环中,而不是单个
    li
    s,您的意思是

    $.each(collection, function(index, value) {
        doms.push($('<li class="item">' + value + '</li>'));
        $('ul.collection-list').append(doms[index]);
    });
    
    doms[2].html('new 3rd li value');
    
    $。每个(集合、函数(索引、值){
    doms.push($);
    $('ul.collection list').append(doms[index]);
    });
    doms[2].html('new 3rd li value');
    
    @TheZ:这是个好问题..正如引用中提到的,jquery不会返回对创建DOM的对象/引用。我该如何“修复”这个是的,我是认真的。那么,我是否正确地理解了我不能做这一行代码,而是必须拆分?@kyogron不必太担心代码行的数量。是的,两行就行了。你可以使用选择器,但正如TheZ所说,这里的两行更好
    doms.push($('ul.collection list').append('
  • '+value+'
  • ')).children(':last')谢谢你的帮助:)现在我可以以和平换和平了