简体   繁体   English

如何在不使用jQuery find()的情况下优雅地读取此DOM对象元素?

[英]How to read this DOM object element elegantly without using jQuery find()?

I got some xml data, parsed it into a dom object so i can search and get values using jQuery. 我得到一些xml数据,将其解析为dom对象,以便我可以使用jQuery搜索和获取值。

Something like this: 像这样:

<field>
    <name>Jesus</name>
    <group>God</group>
    <blah>Hello World</blah>
</field>

In my js, I used an each() to loop through the field: 在我的js中,我使用了each()遍历该字段:

data.find('field').each(function() {
    $(this).find("group").text();
}

I could use find() to fetch each field and content, but I don't want to use find as it could get expensive. 我可以使用find()来获取每个字段和内容,但是我不想使用find,因为它可能会变得昂贵。 I looked through the jQuery API i don't think i there is a function that could let me do something like " getElement('name') " or children('name') or next('name') , etc... 我看过jQuery API,但我不认为我有一个函数可以让我做类似“ getElement('name') ”或children('name')next('name')等的事情。

I don't want to use index either such as $(this)[0].childNodes[0] due to readability and potential future changes. 由于可读性和将来可能发生的变化,我也不想使用诸如$(this)[0].childNodes[0]类的索引。

Any idea? 任何想法?

I'll give you an answer that doesn't use jQuery at all! 我给你一个根本不使用jQuery的答案! How's that? 怎么样?

Your problem seems to be searching through the XML structure. 您的问题似乎是在搜索XML结构。 So you converted it to a DOM tree, but now you're worried about the performance issues of traversing the tree. 因此,您将其转换为DOM树,但是现在您担心遍历该树的性能问题。

The solution is simple: don't convert your XML to HTML, convert it to a JavaScript object literal, and work with that. 解决方案很简单:不要将XML转换为HTML,也不要将其转换为JavaScript对象文字,然后使用它。 It'll be the most simple AND the most efficient. 这将是最简单,最有效的。 For reference to convert XML to an object literal: XML to JavaScript Object 供参考以将XML转换为对象文字: XML到JavaScript对象

Now you are free to use all the tools JavaScript offers to work with your data, and you avoid any jQuery/DOM efficiency problems. 现在,您可以自由使用JavaScript提供的所有工具来处理数据,并且可以避免任何jQuery / DOM效率问题。

function alertit(jqueryObject) {
      if (jqueryObject.length === 0) return;

      jqueryObject.each(function() {
          alert(this.nodeName.toLowerCase());
      });

      alertit(jqueryObject.children());
    }

    alertit($(xml));

also try this 也试试这个

var xmlData = "<field><name>Jesus</name><group>God</group><blah>Hello World</blah></field>";
$(document).ready(function () {
    var data = $.parseXML(xmlData);
    $(data).each(function (i, node) {
        alert($(node).text());
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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