我使用此代码从XML文件获取页面标题。现在,我想显示对应标题的描述,该描述也出现在同一XML文件中。我怎么做?

        var queryObj = new Object();
        var querystring = location.search.replace('?', '');
        var vars = querystring.split("&");
        for (var i = 0; i < vars.length; i++)
        {
            var pair = vars[i].split('=');
            var key = pair[0];
            var value = pair[1];
            var value = decodeURI(value);
            queryObj[key] = value;

        }

        if(queryObj["activity"] != "" && queryObj["phase"] != "")
        {
            $("#TaskTitle").html(queryObj['phase']+": "+queryObj['activity']);
        }

最佳答案

考虑我有这样的XML:

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
   </book> ..so on
</catalog>


我将其存储在字符串中,然后在其上运行parseXML(),将其放入这样的变量中:

var xmlDoc= $.parseXML(myXmlString)


我现在可以将此xmlDoc变量用作DOM对象,并在需要时通过将其传递给$()作为参数遍历它。

$(xmlDoc)


现在,您可以阅读find()closest()等内容,并学习如何在jQuery中遍历。

例如,如果我想获得书籍XML开发人员指南的作者,该指南位于ID为<book>#bk101部分中,则可以这样做:

$(xmlDoc).find("#bk101").find("author")

             //OR

$(xmlDoc).find("#bk101 author")

             //OR

$("#bk101", xmlDoc).find("author")


而已。这是一个演示:http://jsfiddle.net/hungerpain/N3mYa/

08-18 22:53