如何将按钮对象作为函数参数进行传递

How to transfer button object as a function parameter?

本文关键字:参数 函数 按钮 对象      更新时间:2023-09-26

我想使用函数编写以下代码:

<!DOCTYPE html>
<html>
<head>
    <title> Test Java Script</title>
</head>
<body>      
        <button onclick=this.innerHTML=Date();> The Time Is: ? </button>
</body>
</html>

所以我创建了一个函数,并将"this"作为参数传递,但它不起作用:

<!DOCTYPE html>
<html>
<head>
    <title> Test Java Script</title>
</head>
<body>      
    <button onclick=setTime(this)> The Time Is: ? </button>
</body>
        <script type="text/javascript">
            function setTime(Object b) {                
                b.innerHTML=Date();
            }
         </script>
</html>

我做错了什么?

试试这个:

<!DOCTYPE html>
<html>
<head>
    <title> Test Java Script</title>
    <script type="text/javascript">
            function setTime(b) {                
                b.innerHTML=Date();
            }
    </script>
</head>
<body>      
    <button onclick="setTime(this);"> The Time Is: ? </button>
</body>
</html>

向onclick添加引号。从函数声明中删除"Object"。单击按钮。

只需从函数参数中删除Object类型,即可获得黄金:

function setTime(b) {                
    b.innerHTML=Date();
}

正如Katana314在评论中提到的,JavaScript不使用显式类型。

这是一把小提琴:http://jsfiddle.net/3cyj5916/