2013-09-10 65 views
0

如果我知道屬性名稱,是否有更好的方法,更少的密集(我可以有100的OS樣本)寫這個? (「[attribute.name ==''Clear-Matt']」)。$(this).attr('cost');js xml獲取已知屬性的另一個屬性

如果沒有這個函數會在(name ==「Clear-Matt」)時停止,或者它會一直持續到色板的末尾?如果有,是否有辦法阻止它?

var swatchCost=''; 
$(xmldoc).find('Swatch').each(function() { 
     var name = $(this).attr('name'); 
     if (name=="Clear-Matt") { 
      swatchCost=$(this).attr('cost'); 
     } 
}); 

XML:

<Swatch name="Clear" title="Clear" alt="Frame" cost="100" match=""></Swatch> 
<Swatch name="Clear-Matt" title="Clear-Matt" alt="Frame" cost="11" match=""></Swatch> 
<Swatch name="Blue-Orange" title="Blue-Orange" alt="Frame" cost="200" match=""></Swatch> 
<Swatch name="Pink-Blue-Clear" title="Pink-Blue-Clear" alt="Frame" cost="300" match=""> </Swatch> 
<Swatch name="Blue" title="Blue" alt="Frame" cost="11" match=""></Swatch> 

感謝。

回答

1

您可以使用屬性選擇器執行此操作。

$(xmlDoc).find('[name=Clear-Matt]').attr('cost'); // or use 'Swatch[name=Clear-Matt]' 

Fiddle

併爲您現有的for-each循環的問題,一旦你有你需要的你可以做一個return false;這相當於break;聲明什麼。

if (name=="Clear-Matt") { 
     swatchCost=$(this).attr('cost'); 
     return false; //break the iteration now. 
    } 
+0

這很好,謝謝你的答案! – user2238083

+0

@ user2238083不客氣... – PSL