在 casperjs 中将 children 分配给 object

Assign children to object in casperjs

我正在尝试分配给嵌套的 object(在 casperjs 中):

    var yearz = [];
    var yearz2 = $('#form_model optgroup');
    yearz2.each(function() {
        var theyear = $(this).attr('label');        
        var theobj = {
            Year: theyear,
            Thing: [{}]
        };

        for (var i = 0; i < $(this).children().length; i++){
            theobj["Thing"].push({Name: $(this).children()[i].attr("value")});
        }

        yearz.push(theobj);
    });

this.echo(yearz) returnsnull 你能看出问题所在吗?

此致

EDIT

var yearz = [];
var yearz2 = $('#form_model optgroup');
yearz2.each(function() {
    var theyear = $(this).attr('label');
    var lengthch = $(this).children().length; 
    var thisch = $(this).children();      
    var theobj = [];
    var alls = [];

    for (var i = 0; i < lengthch; i++){
        alls.push(thisch.attr("value"));
    }

    theobj = {
        Year: theyear.trim(),
        Thing: alls
    };

    yearz.push(theobj);
});

这会将相同的元素推送到 alls 数组中。但是有两个。我怎么能把他们两个都推,两次都不一样?

这不起作用:

for (var i = 0; i < lengthch; i++){
    alls.push(thisch[i].attr("value")); //Note [i] here.
}

在黑暗中拍摄,因为上下文未知,但请尝试:

var yearz = [];
var yearz2 = $('#form_model optgroup');
yearz2.each(function(i, item) {
    var theyear = $(item).attr('label');        
    var theobj = {
        Year: theyear,
        Thing: [{}]
    };

    for (var i = 0; i < $(item).children().length; i++){
        theobj["Thing"].push({Name: $(item).children()[i].attr("value")});
    }

    yearz.push(theobj);
});
alls.push(thisch[i].attr("value")); //Note [i] here.

这不起作用,因为 [] returns 一个 DOM,而不是 jQuery 对象并且 DOM 没有 .attr()

应该是

thisch.eq(i).val()

thisch[i].value

您也可以只使用 each() 或 map() 而不是 for 循环。

var values = thisch.map( function() { return this.value; } ).get();