javascript - 如何将类作为函数的参数?

标签 javascript html

当我将值作为函数的参数时,

像这样,

<html>
  <head>
    <style rel="stylesheet">
      .A { border: 1px solid red; background-color: white }
    </style>
    <script>
      function clicked(v) {
        console.log(v);
      }
    </script>
  </head>
  <body>
    <input type="button" class="A" value="1" onclick="clicked(value)">
  </body>
</html>

效果不错。

它向我展示了 v 的值(value)。

但是,当我将类作为参数时,

像这样,

<html>
  <head>
    <style rel="stylesheet">
      .A { border: 1px solid red; background-color: white }
    </style>
    <script>
      function clicked(c) {
        console.log(c);
      }
    </script>
  </head>
  <body>
    <input type="button" class="A" value="1" onclick="clicked(class)">
  </body>
</html>

它给我一个错误。

我想让它显示按钮的类选项“A”。

我怎样才能做到?

最佳答案

试试Element.getAttribute()

getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string);

onclick="clicked(this.getAttribute('class'))"

<html>
  <head>
    <style rel="stylesheet">
      .A { border: 1px solid red; background-color: white }
    </style>
    <script>
      function clicked(c) {
        console.log(c);
      }
    </script>
  </head>
  <body>
    <input type="button" class="A" value="1" onclick="clicked(this.getAttribute('class'))">
  </body>
</html>

或:Element.className

className gets and sets the value of the class attribute of the specified element.

onclick="clicked(this.className)"

<html>
  <head>
    <style rel="stylesheet">
      .A { border: 1px solid red; background-color: white }
    </style>
    <script>
      function clicked(c) {
        console.log(c);
      }
    </script>
  </head>
  <body>
    <input type="button" class="A" value="1" onclick="clicked(this.className)">
  </body>
</html>

或者:即使您可以传递this 对象,以便您可以根据需要访问函数内的所有属性:

onclick="clicked(this)"

<html>
  <head>
    <style rel="stylesheet">
      .A { border: 1px solid red; background-color: white }
    </style>
    <script>
      function clicked(c) {
        console.log(c.className);
      }
    </script>
  </head>
  <body>
    <input type="button" class="A" value="1" onclick="clicked(this)">
  </body>
</html>

关于javascript - 如何将类作为函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53465084/

相关文章:

javascript - TypeError : $scope. array.reduce 不是一个函数

javascript - Highcharts : Change opacity of a column chart

java - 如何存储列表中多个项目的全局数组以供以后使用

html - 如何制作文本的 float 标签?

javascript - 使用for循环创建div,h3并在javascript中插入数组变量

javascript - 将属性映射到 react-redux 中的状态

javascript - 如何获取所选行的行索引

html - 如何在不渲染的情况下在 Markdown 文件中键入 html?

php - 如何从 Laravel 中的选择值中获取值

Javascript:使用开-关按钮重复自动刷新网页