简体   繁体   中英

xml js simply find attribute

I'm loading xml and then getting data with js. My question is every time I need to find an attribute do I have to execute a function?

$(document).find("Item").each(function(){
}

I want to say

$(document).find("Item").eq(0).attr("title")

However this only works when I place it in the function

 function parse(document){
 }

This is my xml

 $.ajax({
    url: 'data.xml',
    dataType: "xml",
    success: parse,
    error: function(){alert("Error: Something wrong with XML");}
});

You can use jQuery.parseXML

<html>

    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>

    <body>
        <p id="someElement"></p>
        <p id="anotherElement"></p>
        <script>
            var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
                xmlDoc = $.parseXML(xml),
                $xml = $(xmlDoc),
                $title = $xml.find("title");

            /* append "RSS Title" to #someElement */
            $("#someElement").append($title.text());

            /* change the title to "XML Title" */
            $title.text("XML Title");

            /* append "XML Title" to #anotherElement */
            $("#anotherElement").append($title.text());
        </script>
    </body>

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM