在xml结果中添加onclick事件

时间:2015-05-14 18:45:13

标签: javascript jquery html xml

这是主要的HTML页面。

<html>
<head>
</head>
<body>
    <div class="categories">
        <ul></ul>
    </div>

<script src="script/jquery-1.11.3.min.js"></script>
<script src="script/myscript.js" type="text/javascript"></script>

</body>

</html>

这是xml页面

<CategoriesRoot>
    <Categories>
        <CategoryID>1</CategoryID>
        <CategoryName>Beverages</CategoryName>
        <Description>Soft drinks, coffees, teas, beer, and ale</Description>
    </Categories>
</CategoriesRoot>

这是js页面

$.ajax({

    url:'categories.xml',
    dataType:'xml',
    success: function(data){
        $(data).find('CategoriesRoot Categories').each(function(){
            var name = $(this).find('CategoryName').text();

            $('.categories ul').append(
                $('<li/>',{
                    text: name


                })

            );

        });

    },
    error: function(){
        $('.categories').text('failed');

    }

});

我可以在我的主页面中阅读xml文件,但我想要做的是,当我点击像饮料这样的CategoryName时,它会显示描述(软饮料,咖啡,茶,啤酒和啤酒)。主页右侧。 我是html的新手,请帮助!!

1 个答案:

答案 0 :(得分:0)

我与你分享我在另一篇文章中给出的答案,但它可以帮助你:

how to send the content of a node in xml to another page using php?

问候

<强>版

我将示例代码放在下一个jsFidle示例上。代码很简单。这项工作如下:

  1. 您调用AJAX请求获取XML(line 30)。
  2. 在响应函数(line 33)中,调用构建菜单的函数。
  3. 进入构建功能,您将获得所有类别(line 9)。
  4. 接下来,您将遍历所有类别并构建列表项(line 11 to line 17)。
  5. 最后,您列出一个事件处理程序(line 27)以将锚标记上的click事件捕获到列表中。