[英]How to turn JavaScript array of objects into jQuery prependTo
In the following exampmle I'm setting an array of objects and sort them by a key parameter (position). 在下面的示例中,我设置了一个对象数组,并通过一个关键参数(位置)对它们进行排序。 I then need to output the result - but how?
然后我需要输出结果 - 但是怎么样? See the comment in the code.
请参阅代码中的注释。
$(document).ready(function () {
function sortHooks(){
// add modules
var modules = [
{ module: 'navbar', hook: 'hook-header', position: '2'},
{ module: 'logo', hook: 'hook-header', position: '3'},
{ module: 'description', hook: 'hook-header', position: '1'}
];
// sort by "position" ASC
function byPosition(a,b) {
if (a.position < b.position)
return -1;
if (a.position > b.position)
return 1;
return 0;
}
// jQuery function with the given parameters
/* for each modules as modules
for each hook as hook
do the following:
$( '#' + module )prependTo( '#' + hook )
so for the given example it should return
$('#description')prependTo('hook-header')
$('#navbar')prependTo('hook-header')
$('#logo')prependTo('hook-header')
so they can be executed in that specific order.
And since we're using "prepend" that will mean
that the items be placed like this:
#logo
#navbar
#description
*/
return ???
}
// Execute sortHooks function
sortHooks();
});
Maybe something like this, but I'm not exactly sure: 也许是这样的,但我不确定:
$.each(modules, function(index, value) {
$( '#' + value.module ).prependTo( '#' + value.hook ));
});
I've tried a bunch of other things as well, one of them being Hook elements with insertAfter, but stay in parent - jQuery , which worked perfectly, but if the position was higher than the children inside the parent it didn't know what to do with it and causing a lot of unwanted behavior. 我已经尝试过其他一些东西,其中一个是带有insertAfter的Hook元素,但是留在父 - jQuery ,它工作得很好,但如果位置高于父级内的孩子,它不知道是什么处理它并导致许多不必要的行为。
function byPosition(a,b) { return a.position-b.position; }
modules.sort(byPosition);
modules.forEach(function(obj){
$('#'+obj.madule).prependTo('#'+obj.hook);
});
just use a regular loop 只需使用常规循环
for(var i=0; i<modules.length; i++){
$( '#' + modules[i].module )prependTo( '#' + modules[i].hook );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.