0

目前,我有代码可以将“幻灯片”类的所有子项放入 jQuery 的数组中。

$('.slides').children().each(function (i) {
    var oImg = new Image();
    oImg.src = this.src;
    aImages.push(oImg);         
});

但现在我听说我们必须使用 Javascript 来创建它。我所有将代码段从 jQuery 重新编码为 Javascript 的尝试都失败了。有人知道如何使它工作吗?

4

4 回答 4

2

就像是:

var elements = document.getElementsByClassName("slides");
for(var i in elements){
  var childElements = elements[i].children;
  for(var j in childElements){
     var child = childElements[j];

     //your code here
  }
}
于 2013-04-23T08:30:19.623 回答
2

尝试这个:

// Get all the elements with class 'slides'
var elements = document.getElementsByClassName('slides');

// Loop through all the elements first...
for (var j = 0; j < elements.length; j++) {

    // Get all the childNodes within each class 'slides'
    var children = elements[j].childNodes;

    // Loop through all the childrens
    for (var i = 0; i < children.length; i++) {
        var oImg = new Image();
        oImg.src = children[i].src;
        aImages.push(oImg);
    }
}
于 2013-04-23T08:25:29.330 回答
0

尝试

var aImages = [];

// get all elements with class slides
var slides = document.getElementsByClassName('slides');

// iterate through the slides array
for (var i = 0; i < slides.length; i++) {
    var slide = slides[0];

    // iterate through each child of slide
    for (var j = 0; i < slide.childNodes.length; i++) {
        var child = slide.childNodes[j];
        var oImg = new Image();
        oImg.src = this.src;
        aImages.push(oImg);
    }
}
于 2013-04-23T08:30:01.073 回答
0

尝试这个:

    var elements = document.getElementsByClassName('slides');
    var myImages = elements.getElementsByTagName("img");

    for (var i = 0; i < myImages.length; i++) {
        var oImg = new Image();
        oImg.src = myImages[i].src;
        aImages.push(oImg);
    }
于 2013-04-23T08:28:04.573 回答