如何使用jquery获得Xml属性?

How can I get an Xml attribute with jquery?

本文关键字:属性 Xml 获得 何使用 jquery      更新时间:2023-09-26

我有以下XML:

<Openings width="20" height="10" layers="1">
  <opening>
    <item>
      <x>1.5</x>
      <y>2.25</y>
      <width>3.5</width>
      <height>5.5</height>
      <type>rectangle</type>
    </item>
  </opening>
</Openings>

我有以下javascript代码:

$(openings).each(function(j, opening_el)
{
  console.log("layers: " + $(opening_el).attr("layers")); //This is not working
});

我想让它打印出"layers: 1";

是否有帮助

$("Openings").attr("layers")

如果有帮助,请告诉我。

您在openings标签上调用jQuery时缺少引号,并使用this在循环中获取html元素的当前实例

$('Openings').each(function(j, opening_el)
{
  console.log("layers: " + $(this).attr("layers"));
});
演示工作

是的,你已经说过了。这个版本应该可以正常工作。

$('openings').each(function(j, opening_el)
{
  console.log("layers: " + $(opening_el).attr("layers")); //This is working
});

首先,您有不正确的选择器与标签打开目标dom。应该是$('Openings')。您还需要使用$(this)来访问.each()循环中的当前dom。

试试这个:

 $('Openings').each(function(){
     console.log("layers: " + $(this).prop("layers")); 
 });