51

メソッドを使用して個々の属性を取得できることは知っていますが、要素のすべてattr()の属性を反復処理しようとしています。コンテキストとして、私はいくつかのXMLでjQueryを使用しています...

<items>
  <item id="id123" name="Fizz" value="Buzz" type="xyz">
    <subitem name="foo">
    <subitem name="bar">
  </item>
  <item id="id456" name="Bizz" value="Bazz" type="abc">
    <subitem name="meh">
    <subitem name="hem">
  </item>
</items>

私はすでにアイテムを繰り返すことができます...

$(xml).find('item').each(function() {
  // Do something to each item here...
});

ただし、「アイテム」ごとに属性の配列を取得できるようにしたいので、それらを反復処理できます...

例えば

$(xml).find('item').each(function() {
  var attributes = $(this).attributes(); // returns an array of attributes?
  for (attribute in attributes) {
    // Do something with each attribute...
  }
});

ここ、jQueryのドキュメント、およびGoogleを介した他の場所で検索を行いましたが、うまくいきませんでした。他に何もないとしてもattr()、jQueryオブジェクトのメソッドに関連する結果を除外するのに問題があるだけかもしれません。前もって感謝します。

4

8 に答える 8

109

attributes最良の方法は、そのプロパティを使用してノードオブジェクトを直接使用することです。この方法を示唆している他のソリューションと比較した以下の私のソリューションの唯一の違いは.each、従来のjsループの代わりに再び使用することです:

$(xml).find('item').each(function() {
  $.each(this.attributes, function(i, attrib){
     var name = attrib.name;
     var value = attrib.value;
     // do your magic :-)
  });
});
于 2010-02-08T21:27:44.110 に答える
12

プレーンな古いバニラJavaScriptを使用する必要があるようです。

for (var i = 0; i < elem.attributes.length; i++) {
    var attrib = elem.attributes[i];
    if (attrib.specified == true) {
        console.log(attrib.name + " = " + attrib.value);
    }
}

HTML要素のすべての属性を反復処理するにはどうすればよいですか?

于 2010-02-08T21:23:00.127 に答える
4

get()関数を使用してjQueryラッパーからDOM要素を取得し、DOM属性を繰り返すことができますか?

var node = $(myStuff).get(0);
if (node.attributes.length) {

    for (var length = attrs.length, i = 0; i < length; i++) {
        if (attrs[i].specified) {

        }
    }
}

より堅牢なDOM属性処理については、このブログ投稿を確認してください

于 2010-02-08T21:24:44.087 に答える
1

私がここに投稿しているのは、この投稿にたどり着いた他の人が、私がそうであったようにxmlファイルを解析しようとしているのに役立つと思うからです。

theracoonbearのファイルと非常によく似た構造のxmlファイルをトラバースし、結果を配列に格納する方法を探していたところ、この投稿に出くわしました。

私はprodigitalsonのコードを見ましたが、この構文を機能させることができませんでした-Firefoxが次の行でそれを不平を言っています:

 $.each(this.attributes, function(i, attrib){

それ

this.attributes

定義された関数ではありません。 エラーは完全に私のものであると確信しています。しかし、私はこれを機能させるために数時間を費やし、失敗しました

私のために働いたのは(私のタグ名がアイテムではなくセッションである場合):-

$(xml_Data).find("session").each(function() {
    console.log("found session");
    $(this).children().each(function(){
     console.log("found child " + this.tagName);
     console.log("attributes" + $(this).text());
    });
});

これが元の質問に正確に答えないかもしれないことを感謝します。しかし、それがこの投稿への他の訪問者をいつか救うかもしれないことを願っています。

よろしく

于 2012-09-10T17:43:12.293 に答える
1

どうですか?

$(xml).find('item').each(function() {
  var attributes = $(this)[0].attributes;
  for (attribute in attributes) {
    // Do something with each attribute...
  }
});
于 2010-02-08T21:24:15.150 に答える
1

標準のDOMElement属性を使用することもできますが、IE6のすべての属性(明示的に設定されていない属性も含む)attributesが含まれます。別の方法として、設定する属性の数を制限することができます。

var use_attributes = ['id','name','value','type'];
$(xml).find('item').each(function() {
  var $item = $(this);

  $.each( use_attributes, function(){
    if($item.attr( this )){
      // Act on the attribute here. 
      // `this` = attribute name
      // $item.attr( this ) = attribute value
    }
  })
});
于 2010-02-08T21:28:56.027 に答える
1

innearHtmlだけでなく属性も調べることができるこのジェネリック関数を作成しました。

function findByAll(toLookFor, lookInText) { 
    return $('*').filter(function() { 
        return Array.prototype.some.call(this.attributes, function(attr) {
            return attr.value.indexOf(toLookFor) >= 0; 
        }) || (lookInText && $(this).text().indexOf(toLookFor) >= 0); 
    }); 
}
于 2016-07-05T19:58:18.947 に答える
-1

Pure JSまず、入力xmlは無効ですが、サブアイテムタグを閉じることで修正できます。/

let items = (new DOMParser()).parseFromString(xml,"text/xml").querySelectorAll('item');

items .forEach( (item,i)=> Object.values(item.attributes).forEach(a => {
  // your code
  console.log(`Item ${i}. attr ${a.name} = ${a.value}`)
}));

let xml=`<items>
  <item id="id123" name="Fizz" value="Buzz" type="xyz">
    <subitem name="foo" />
    <subitem name="bar" />
  </item>
  <item id="id456" name="Bizz" value="Bazz" type="abc">
    <subitem name="meh" />
    <subitem name="hem" />
  </item>
</items>`;

let items  = (new DOMParser()).parseFromString(xml,"text/xml").querySelectorAll('item');

items .forEach( (item,i)=> Object.values(item.attributes).forEach(a => {
  // your code
  console.log(`Item ${i}. attr ${a.name} = ${a.value}`)
}));

于 2019-01-25T13:10:22.550 に答える