jquery - 获取具有最高属性值的元素

时间:2014-04-24 12:28:29

标签: jquery xml parsing

如何获取attribut名称等于'temp'且具有最高attribut值的元素?

XML

<el>
   <em name="temp" value="5">
      <data>nok</data>
   </em>
   <em name="other" value="10">
      <data>nok</data>
   </em>
   <em name="temp" value="8">
      <data>ok</data>
   </em>
</el>

我拥有的实际代码:

JQUERY

var name= 'temp';

$xml.find("em[name=" + name + "]").each(function() {
    $(this).find( "data" ).each(
        function(){
            alert($(this).text());
        } 
    );                             
});

3 个答案:

答案 0 :(得分:1)

试试这个,评论不言而喻我希望......

 // var for the highest value
 var highestval = 0;

 // the element we are seeking
 var highestvalelement;

 // loop through the em elements
 $xml.find("em[name=" + name +"]").each(
    function()
    {
       // the value attribute of this element
       elval = $(this).attr('id')

       // is it the highest
       if(elval >= highestval)
       {
           // set the highest value
           highestval = elval;

           // store the object
           highestvalelement = $(this);
       }         
    }
 );

 // highestvalelement will contain the em elemnt with the highest value

答案 1 :(得分:0)

试试这个:

 var valArray = [];
 $xml.find('em[name=temp]').each(function(){
   valArray.push(parseInt($(this).attr('value'), 10));
 })
 valArray.sort(function(a, b) { return a - b })

 valArray[0] // lowest
 valArray[valArray.length - 1] // highest`

<强> Working Demo

<强> Reference

答案 2 :(得分:0)

var name= 'temp';
$xml.find("em[name=" + name + "]").each(function() {
$(this).find( "data" ).each(function(){
                                    alert($(this).innerhtml());
                                 });   
});

为了更好的答案,请告诉我们错误.......

相关问题