简体   繁体   English

如何从元素数组中获取元素并渲染它?

[英]how to get element from array of elements and render it?

I have array of elements I would like to find an element from array by class and I need to separate the element from array? 我有一些元素我希望从类中找到一个元素,我需要将元素与数组分开?

var mainEl=$(htmlContent);

/*
mainEl:

[el1,el2.classItem,el3#funID]

*/
var needEl;
mainEl.each(function(){
if($(this).hasClass("classItem"))
 needEl=$(this)
});

//render content without needEl
$(".container").append(mainEl);
//render seperatly needEl
$(".separate").append(needEl);

But this is not working as Expected, 但这不符合预期,

is there any simple way to do it or am I doing wrong? 有什么简单的方法可以做到这一点,还是我做错了?

There are a number of ways you could do this. 有很多方法可以做到这一点。 If I understand you right, this is one good way: 如果我理解你,这是一个好方法:

var $content = $(htmlContent);
var $separate = $content.filter('.classItem');
var $main = $content.not( $separate );
$(".container").append( $main );
$(".separate").append( $separate );

This is pretty straightforward when you use the following helper function: 使用以下辅助函数时,这非常简单:

$.fn.others = function() {
    return this.end().not(this);
};

It effectively reverses the previous operation. 它有效地逆转了以前的操作。 This is how you could use it: 这是你如何使用它:

$(htmlContent)
    .filter('.classItem') // take .classItem first
      .appendTo('.separate') // and append to separate
    .others() // take the remaining items
      .appendTo('.container'); // and append to main

It'd be easier to help you if you described in greater detail what you mean by "not working as Expected". 如果您更详细地描述了“不按预期工作”的含义,那么帮助您会更容易。 You're not removing needEl from the mainEl collection, that would be one issue. 你没有从mainEl集合中删除needEl ,这将是一个问题。

You could do something like this: 你可以这样做:

var mainEl = $(htmlContent);
$('.container').append( mainEl.filter(function() { return !$(this).hasClass('classItem');  }) );
$('.separate').append( mainEl.filter(function() { return $(this).hasClass('classItem');  }) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM