【问题标题】:Dynamically add images to jQuery from xml从 xml 动态地将图像添加到 jQuery
【发布时间】:2014-08-26 17:43:59
【问题描述】:

我正在尝试将 XML 文件中的一系列图像添加到 html 中并将它们显示为幻灯片。我有幻灯片代码工作,但只添加了第一张图片。这些图像被称为“Slide1.png”、“Slide2.png”等。但是,当我将$('body').append('<div id="container" />'); 替换为$('body').append('<div />'); 并将$('#container').append($(pic)); 替换为$('div').append($(pic)); 时,它可以工作,但我不知道为什么。

jQuery 代码如下:

<script>
 $(document).ready(function()
      {
        var temp = "";
        var i = 1;
        $.get('myData.xml', function(d){

        $('body').append('<div id="container" />');

        var fcn = $(d).find('picture').each(function(){

            var $image = $(this);
            var title = $picture.attr("title");
            var imageurl = $picture.attr('imageurl');
            var time_duration = $picture.attr("time_duration");

            var pic = '<li> <img class="bookImage" alt="" src="' + "images/Slide" + i + ".png "+ '" /> </li>';
            $('#container').append($(pic));
            i++;


        });
    });

// Slideshow Code
// ...
});
</script>

【问题讨论】:

    标签: jquery xml image slideshow


    【解决方案1】:

    我对您的示例代码提出了一些可能有助于解决此问题的建议。

    //adding a ul to contain the li, this may not be needed
    $('body').append('<div id="container"><ul/></div>');
    
        //add your index variable to the each function if it is needed
        var fcn = $(d).find('picture').each(function(i){
    
            //variable was previously named $image, but was not used.
            var $picture= $(this);
            var title = $picture.attr("title");
            var imageurl = $picture.attr('imageurl');
            var time_duration = $picture.attr("time_duration");
    
            //make pic a jquery variable to simplify attribute setting
            var pic = $('<li> <img class="bookImage" alt=""/> </li>');
            pic.attr(src,imageurl); //prefix with path if needed
    
            //add results to the ul
            $('#container ul').append(pic);
         });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      相关资源
      最近更新 更多