jQuery - get a list of values of an attribute from elements of a class

后端 未结 5 2051
北荒
北荒 2020-12-04 07:34

I have a class .object which has an attribute called level. I want to get a list of all the different values of level on the page so I

相关标签:
5条回答
  • 2020-12-04 08:15

    $(".object").attr("level") will just return the attribute of first the first .object element.

    This will get you an array of all levels:

    var list = $(".object").map(function(){return $(this).attr("level");}).get();
    
    0 讨论(0)
  • 2020-12-04 08:21

    First part of the question, getting the attribute values into an array. See this question

    jQuery get img source attributes from list and push into array

    You would say

    var levelArray = $('.object').map( function() {
        return $(this).attr('level');
    }).get();
    

    Second part of the question , you can use this technique to get the highest value

    var maxValue = Math.max.apply( Math, levelArray );
    
    0 讨论(0)
  • 2020-12-04 08:30

    the selector

    $(".object[level]")
    

    will give you all the dom elements with class object and an attribute level.

    Then you can just use the .each() method to iterate over the elements to get the highest value

    0 讨论(0)
  • 2020-12-04 08:35

    You can extend the functionality of Jquery and add your own 'attrs' implementation.

    Add the following lines of code to your JavaScript file:

    jQuery.fn.extend({
        attrs: function (attributeName) {
            var results = [];
            $.each(this, function (i, item) {
                results.push(item.getAttribute(attributeName));
            });
            return results;
        }
    });
    

    Now you can get the list of level values by calling:

    $(".object").attrs("level")
    
    0 讨论(0)
  • 2020-12-04 08:38
    <script type="text/javascript"> 
    var max = 0;
    jQuery(document).ready(function(){ 
        jQuery('.object[level]').each(function(){
            var num = parseInt($(this).attr('level'), 10);
            if (num > max) { max = num; }
        });
        alert(max);
    });
    </script>
    

    I'm assuming markup like this:

    <div class="object" level="1">placeholder</div>
    <div class="object" level="10">placeholder</div>
    <div class="object" level="20">placeholder</div>
    <div class="object" level="1000">placeholder</div>
    <div class="object" level="40">placeholder</div>
    <div class="object" level="3">placeholder</div>
    <div class="object" level="5">placeholder</div>
    

    For my code I get "1000" alerted to me.

    Here's another solution, combining several of the other replies from harpo, lomaxx, and Kobi:

    jQuery(document).ready(function(){ 
        var list = $(".object[level]").map(function(){
            return parseInt($(this).attr("level"), 10);
        }).get();
        var max = Math.max.apply( Math, list ); 
        alert(max);
    });
    
    0 讨论(0)
提交回复
热议问题