【问题标题】:show button class name on click using javascript使用javascript单击时显示按钮类名
【发布时间】:2013-04-23 15:06:50
【问题描述】:

您好,我有一个要求,我需要显示使用java script 单击的按钮的类名。有很多不同类名的按钮。有什么建议吗?

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFunction()
{
var container = document.getElementById(id);
alert (container);
}
</script>
</head>
<body>


<button class="A" id="A" onclick="myFunction()">A</button>
<button class="B" id="B" onclick="myFunction()">B</button>
<button class="C" id="C" onclick="myFunction()">C</button>
<button class="D" id="D" onclick="myFunction()">D</button>

</body>
</html>

【问题讨论】:

标签: javascript html css


【解决方案1】:

您可以使用dom elementclassName property 来获取类名。

<button class="A" onclick="myFunction(this)">A</button>
<button class="B" onclick="myFunction(this)">B</button>
<button class="C" onclick="myFunction(this)">C</button>
<button class="D" onclick="myFunction(this)">D</button>

function myFunction(el) {
    alert (el.className);
}

演示:Fiddle

【讨论】:

    【解决方案2】:

    这就是你要找的吗?

     window.onclick = function(e) {
         console.log(e); // then e.srcElement.className has the class
     }​
    

    http://jsfiddle.net/M2Wvp/

    https://stackoverflow.com/a/3774720/1172872

    【讨论】:

      【解决方案3】:

      试试看

      <button id="A" class="b" onclick="myFunction(this)">A</button>
      

      并访问类名

      function myFunction(el)
      {
          console.log(el.className);
      }
      

      这是demo fiddle

      【讨论】:

        猜你喜欢
        • 2021-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-07
        • 1970-01-01
        • 1970-01-01
        • 2013-05-11
        相关资源
        最近更新 更多