【问题标题】:Getting data from xml to insert into html tag but It is not seen in source code从 xml 获取数据以插入 html 标记,但在源代码中未显示
【发布时间】:2013-08-25 10:18:29
【问题描述】:

从 xml 获取数据以插入 ul 标记。当我运行代码时,页面正在加载,我可以在浏览器上看到图像,但 jquery 代码不起作用(例如单击 #GalleryList 元素),因为在浏览器视图源中看不到附加代码。如何找到解决方案?

JS:

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "data.xml",
        dataType: "xml",
        success: function (xml) {
            var items = [];
            $(xml).find("item").each(function (i) {
                items.push({
                    img: $(this).find("img").text(),
                    content: $(this).find("content").text()
                });
                $('#GalleryList').append('<li>' + items[i].img + '</li>');
                $('#GalleryDetail').append('<li><div class="detailLeft">' + items[i].img + '</div><div class="detailRight">' + items[i].content + '</div></li>');
                i++;
            });
            return items;
        }
    });
    var currentElem, lastElem;
    lastElem = $('#GalleryList li').last().index();
    $('#GalleryList li').click(function () {
        currentElem = $(this).index() + 1;
        $('#GalleryList').hide();
        $('.GalleryDetail').show();
        $('#GalleryDetail li').hide();
        $('#GalleryDetail li:nth-child(' + currentElem + ')').show();
        pageControl();
    });
});

HTML:

<ul id="GalleryList" class="clearfix">

</ul>
<div class="GalleryDetail">
   <ul id="GalleryDetail">

   </ul>
</div>

【问题讨论】:

  • 添加到客户端页面的元素永远不会在源中可见。 source 仅显示页面的来源是什么,即从服务器返回的内容。

标签: javascript jquery html xml ajax


【解决方案1】:

您需要使用事件委托,因为li 元素是动态创建的

$('#GalleryList').on('click, 'li', function () {
    currentElem = $(this).index() + 1;
    $('#GalleryList').hide();
    $('.GalleryDetail').show();
    $('#GalleryDetail li').hide();
    $('#GalleryDetail li:nth-child(' + currentElem + ')').show();
    pageControl();
});

【讨论】:

    【解决方案2】:

    使用$.on("click",.. 而不是$.clickhttp://api.jquery.com/on/

    【讨论】:

      【解决方案3】:

      您应该使用on 将事件绑定到动态创建的元素:

      $('#GalleryList li').on('click', function ()
      

      【讨论】:

        猜你喜欢
        • 2011-05-13
        • 2012-11-08
        • 2017-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-29
        • 1970-01-01
        相关资源
        最近更新 更多