繁体   English   中英

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

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

我有一些元素我希望从类中找到一个元素,我需要将元素与数组分开?

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);

但这不符合预期,

有什么简单的方法可以做到这一点,还是我做错了?

有很多方法可以做到这一点。 如果我理解你,这是一个好方法:

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

使用以下辅助函数时,这非常简单:

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

它有效地逆转了以前的操作。 这是你如何使用它:

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

如果您更详细地描述了“不按预期工作”的含义,那么帮助您会更容易。 你没有从mainEl集合中删除needEl ,这将是一个问题。

你可以这样做:

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