javascript 如何选择具有相同类名的所有元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16985841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:40:57  来源:igfitidea点击:

How can I select all elements with the same class name?

javascriptjquery

提问by Josh-Mason

I have a Boolean variable. It is stored in a hidden input field. Basically, if the user is signed in, it is false, if not, it is true.

我有一个布尔变量。它存储在隐藏的输入字段中。基本上,如果用户已登录false,则为 ,否则为true

There are download buttons which will link to a file download. My aim is to make it so that, if they aren't signed in, the button will not show, and the link will not work (it would be nice to have an alert saying they need to sign in or something, but that would probably be more effort than it's worth).

有下载按钮将链接到文件下载。我的目标是做到这一点,如果他们没有登录,按钮将不会显示,并且链接将不起作用(有一个警告说他们需要登录或其他东西会很好,但这会可能比它的价值更多的努力)。

I have a function that performs onloadof body:

我有一个执行onload身体的功能:

function hide_download_btns(){
if (document.getElementById('download_btn_var_input').value == "true") {
    document.getElementsByClassName('project_download_btn').item(0).hidden = true
    }
}

My problem is where it asks for the nth term .item(0). This is where it selects the div on which to perform the function, however, I want the function to affect alldivs with the class name 'project_download_btn'.

我的问题是它要求 nth term 的地方.item(0)。这是它选择要执行该函数的 div 的地方,但是,我希望该函数影响所有div类名为“project_download_btn”的 s。

I'm not a fan of jQuery, so it would be great to avoid that if possible.

我不是 jQuery 的粉丝,所以如果可能的话,最好避免这种情况。

回答by James Montagne

You can simply loop through the elements instead of just taking the 0th.

您可以简单地循环遍历元素,而不仅仅是取第 0 个。

var buttons = document.getElementsByClassName('project_download_btn');

for(var i=0; i< buttons.length; i++){
    buttons[i].hidden = true;
}

回答by Daniel Dykszak

document.getElementsByClassNamereturns array so what you are interested is :

document.getElementsByClassName返回数组所以你感兴趣的是:

document.getElementsByClassName('project_download_btn')[0]

回答by Mohammad Adil

if (document.getElementById('download_btn_var_input').value == "true") {
    var el = document.getElementsByClassName('project_download_btn');
    for (var i = 0; i < el.length; i++) {
        el[i].hidden = true;
    }
}

回答by Dusty

Loop through each divthat contains your download button and set hiddento true:

遍历每个div包含您的下载按钮并设置hiddentrue

if (document.getElementById('download_btn_var_input').value == "true") {
    var button_divs_array = document.getElementsByClassName('project_download_btn');
    for (var i = 0; i < button_divs_array.length; i++) {
        button_divs_array[i].hidden = true;
    }
}