【问题标题】:jquery - get element with the highest attribut valuejquery - 获取具有最高属性值的元素
【发布时间】:2014-06-09 17:43:03
【问题描述】:

如何获取属性名称等于“temp”且属性值最高的元素?

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());
        } 
    );                             
});

【问题讨论】:

    标签: jquery xml parsing


    【解决方案1】:

    试试这个,cmets自己说话我希望...

     // 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
    

    【讨论】:

    • 它也是正确的,但我认为@Milind 的解决方案在性能方面更好......我实际上不知道:)
    【解决方案2】:

    试试这个:

     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

    【讨论】:

    • 谢谢。我编辑了我的帖子,因为我只想获取属性名称等于“temp”的元素。然后我想返回要解析的元素。
    • @Jils:我已经更新了获取 name=temp。你还想要什么。
    • 这在我的真实代码中有效,谢谢。有一种方法可以获取相应的“em”元素,例如 $em?
    • 将 $(this) 存储在数组中,而不是 $(this).attr('value')。然后你可以访问它 valArray[i]
    【解决方案3】:
    var name= 'temp';
    $xml.find("em[name=" + name + "]").each(function() {
    $(this).find( "data" ).each(function(){
                                        alert($(this).innerhtml());
                                     });   
    });
    

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

    【讨论】:

    • 没有错误,我只是没有找到想要的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 2015-10-01
    相关资源
    最近更新 更多