【问题标题】:jQuery XML parsing how to get element attributejQuery XML解析如何获取元素属性
【发布时间】:2011-01-28 07:37:55
【问题描述】:

XML:

<item>
     <title>Some title</title>

     <description>
     <![CDATA[
      Some description text Some description text Some description text Some description text Some description text Some description text 
      Some description text Some description text Some description text Some description text Some description text Some description text 
      Some description text Some description text Some description text Some description text Some description text Some description text 
      Some description text Some description text Some description text Some description text Some description text Some description text 
     ]]>
     </description>

     <media:content isDefault="true" medium="image" url="http://sampledomain.com/image.jpg">
      <media:title>Image title</media:title>
      <media:description>Image description</media:description>
      <media:thumbnail url="http://sampledomain.com/image.jpg" width="160" height="120" />
     </media:content>

     <wfw:commentRss>http://sampledomain.com/comment/feed/</wfw:commentRss>
     <slash:comments>0</slash:comments>
    </item>

我正在从 ajax 获取 css,在 onsuccess 函数中我的代码如下:

$(xml).find('item').each(function() {
 var title = $(this).find('title').eq(0).text();
 var url   = $(this).find('content').attr('url');

 // Printing url as undefined
 alert(url);
 console.log($(this).find('content');

});

我想要获取内容 url 属性我正在获取子项(标题、描述、内容、commentRss 和 cmets) 但是当我尝试获取 $(this).find('content') 它没有给我任何东西 谁能弄清楚我做错了什么? 谢谢

【问题讨论】:

  • var url=$(this).find('content').attr('url').val();或尝试使用 .text() 希望对您有所帮助

标签: jquery xml


【解决方案1】:

您的 XML 使用命名空间。

查看有关命名空间的类似 Stack Overflow 问题。你必须转义冒号:

jQuery XML parsing with namespaces

【讨论】:

  • 感谢这个对我有用的链接 $(this).find('media\\:content').attr('url');
  • @shankhan - 不客气。这绝对是件好事。我不经常处理命名空间,但我自己正在计划一个涉及它们的项目。
【解决方案2】:

为您提供更正.. 以及您的命名空间解决方案! 您需要使用 \ 正确转义命名空间“:”。我已经展示了下面的示例,该示例适用于 Itunes 播客 XML 提要。

 item.description = jQuery(this).find("[nodeName=itunes\\:summary]").eq(0).text();

【讨论】:

    猜你喜欢
    • 2012-03-03
    • 2012-04-14
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 2011-12-06
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多