Javascript:一次调用多个GetElementByID [英] Javascript: Multiple GetElementByID's in one call

查看:92
本文介绍了Javascript:一次调用多个GetElementByID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

真的很简单的问题。我有以下代码,并希望尽可能地将其合并。不能让它工作,虽然..尝试使用逗号等。有没有办法在GetElementByID方法中调用多个ID? Javascript新功能:/ b /

$ $ $ $ $ $ $#set50。live(click,function(){
document.getElementById(statusBox50)。setAttribute(class,statusBoxSelected);
document.getElementById(statusBox25)。setAttribute(class,statusBox);
document .getElementById(statusBox75)。setAttribute(class,statusBox);
document.getElementById(statusBox100)。setAttribute(class,statusBox);
$( .statusbar)。animate({
width:'115px'
},500);
});


解决方案

不,但由于您使用jQuery,你可以使用它。这会将 statusBox 类添加到ID statusBox25 statusBox75 statusBox100

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

或者,如果您想删除所有现有的类并将它们全部替换为<$ c $

  $(#c> statusBox 就像你原来的代码一样,你可以使用这个: statusBox25,#statusBox75,#statusBox100)。attr('class','statusBox'); 


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 a way to call more than one ID in the GetElementByID method? New to Javascript : /

$("#set50").live("click", function() {
    document.getElementById("statusBox50").setAttribute("class", "statusBoxSelected");
    document.getElementById("statusBox25").setAttribute("class", "statusBox");
    document.getElementById("statusBox75").setAttribute("class", "statusBox");
    document.getElementById("statusBox100").setAttribute("class", "statusBox");
    $(".statusbar").animate({
        width: '115px'
    }, 500);    
});

解决方案

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');

这篇关于Javascript:一次调用多个GetElementByID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆