[removed] Multiple GetElementByID's in one call

前端 未结 4 860
我在风中等你
我在风中等你 2020-12-20 06:58

Really simple question. I have the following code, and would like to consolidate it down as much as possible. Can\'t get it to work though.. tried using commas etc. Is there

相关标签:
4条回答
  • 2020-12-20 07:25

    Is there a way to call more than one ID in the GetElementByID method?

    No, and it is Id (with a lower case d)

    And don't use setAttribute, it is broken in all but the most recent versions of IE.

    You're using jQuery, so you can use its helper functions:

    jQuery('#statusBox50').addClass('statusBoxSelected');
    jQuery('#statusBox25, #statusBox75, #statusBox100').addClass('statusBox');
    
    0 讨论(0)
  • 2020-12-20 07:31

    No, but since you're using jQuery anyway, you can use that. This will add the statusBox class to the elements with the IDs statusBox25, statusBox75, and statusBox100:

    $("#statusBox25, #statusBox75, #statusBox100").addClass('statusBox');
    

    Alternatively, if you want to remove all of the existing classes and replace them all with statusBox like your original code as doing, you could use this:

    $("#statusBox25, #statusBox75, #statusBox100").attr('class', 'statusBox');
    
    0 讨论(0)
  • 2020-12-20 07:38

    You should be able to do something like:

    $("#set50").live("click", function() {
        $("#statusBox50").addClass("selected");
        $("#statusBox25, #statusBox75, #statusBox100").removeClass("selected");
        $(".statusbar").animate({...});
    });
    

    Note that I am doing something different to you: I have a class "selected" that I either apply or remove, rather than setting the classes of [statusBoxSelected|statusBox]. This could be in addition to a class="statusBox".

    I'd also recommend you look at other ways that don't hard-code the ids like that. For instance:

    $(".set50").live("click", function(evt) {
        $('.statusBar').removeClass("selected");
        $('#statusBar50').addClass("selected");
    });
    

    You could even go further, and have an attribute on the "set" elements that contained the amount the status bar should be set to.

    Or consider using an HTML5 progress bar, and some shims to do the same in non-supported browsers.

    0 讨论(0)
  • 2020-12-20 07:44
    $("#set50").live("click", function() {
        $("statusBox50").addClass("statusBoxSelected");
        $("statusBox25").addClass"statusBox");
        $("statusBox75").addClass( "statusBox");
        $("statusBox100").addClass( "statusBox");
        $(".statusbar").animate({
            width: '115px'
        }, 500);    
    });
    

    is this what u want ?

    .addClass adds a class to the selected element.[docs]

    EDIT: As u said u want a single. Just assign a class to all the elements u want to add the class. For eg: i assign the class adding. then u can addclass to all the elements like this :

    $('.adding').addClass('statusBox')
    
    0 讨论(0)
提交回复
热议问题