获取外部js文件Javascript中单击html元素的Classname?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (125)

我正在尝试获取单击的html元素的类名。

我的HTML代码:

<a href="#" class="btn myButton1"><i class="fas fa-times"></i> <span>Button 1</span></a>
<a href="#" class="btn myButton2"><i class="fas fa-times"></i> <span>Button 2</span></a>

单击一个元素时,我希望在变量中保存元素=类的名称。

myButton1 / myButton2
btn myButton1 / btn myButton2
...
case: 'user_admin':
<a href="#" class="btn myButton1"><i class="fas fa-times"></i> <span>Button 1</span></a>
    <a href="#" class="btn myButton2"><i class="fas fa-times"></i> <span>Button 2</span></a>
...

当按钮被点击时,我会检查一下方法。

else {
                if (modus == 'user') {
                  public.user();
                }
                else if (modus == 'admin') {
                  public.admin();
                }
                else if (modus == 'user_admin') {
                  public.user_admin();
                }
            }

在if-语句之后,我调用函数。在这里,我想检查一下按钮1是.还是按钮2那么.

public.user_admin = function () {

//myCODE...

...
}

这有可能吗?

<script type="text/javascript">
var buttons = document.getElementsByTagName('a');
    for (var i = 0; i < buttons.length; i++) {
            var button = buttons[i];
            button.addEventListener("click", function(){

                    console.log(this.className); --> Is working in index.php

            })
            var clickedElement = this.className; --> Is not working in index.php (undefined)
            console.log("Clicked: "+clickedElement); --> Is not working in index.php (undefined)
    }
</script>

我的JS档案:

    public.user_admin = function () {

console.log(this.className); --> undefined
console.log(clickedElement); --> undefined


...}
提问于
用户回答回答于

可以根据单击的内容对变量进行范围调整。

let arrayOfAnchors = document.querySelectorAll('a');
arrayofAnchors.forEach(anchor => {
    console.log(anchor.className);
    console.log(anchor.classList);
    anchor.addEventListener('click', function() { console.log('hey there'); alert('hi'); });

});
用户回答回答于

可以使用.className

var buttons = document.getElementsByTagName('a');
for (var i = 0; i < buttons.length; i++) {
    var button = buttons[i];
    button.addEventListener("click", function(){
        console.log(this.className)
    })
}
<a href="#" class="btn myButton1"><i class="fas fa-times"></i> <span>Button 1</span></a>
<a href="#" class="btn myButton2"><i class="fas fa-times"></i> <span>Button 2</span></a>

扫码关注云+社区

领取腾讯云代金券