相同类名但不是同级别的最后一个元素,如何选择具有相同类名的所有元素?

本文介绍如何使用JavaScript在网页中实现用户登录状态检查,以隐藏未登录用户的下载按钮,避免非法下载。通过遍历class为'project_download_btn'的所有元素并设置其hidden属性,实现了不依赖jQuery的简单解决方案。
摘要由CSDN通过智能技术生成

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.

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 onload of body:

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 all divs with the class name 'project_download_btn'.

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

解决方案

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

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

for(var i=0; i< buttons.length; i++){

buttons[i].hidden = true;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值