JavaScript,将 id 作为参数传递给函数

标签 javascript html

我有<td> ID <td id="firstApp"> .我已经为按钮写了 onclick 事件。单击按钮时 showDate函数被调用。我想将“id”作为参数传递给这个 showDate 函数,这样我的函数就会知道它应该作用于哪个 id。

我试过了,

<td><button type="button" onclick='document.getElementById("firstApp").innerHTML=Date()'>

然后它工作正常。

但是当我将 id 作为函数调用传递时,

<td><button type="button" onclick='showDate("firstApp")'>

然后就不行了,谁能告诉我哪里错了...!!

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <tr>
            <td>App 1</td>
            <td><button type="button" onclick='showDate("firstApp")' name="app1" >on/off</td>
            <td>10</td>
            <td id="firstApp"></td>
            <td></td>
        </tr>
        <!--    <button type="button">Update</button> <button type="button">Log Out</button> -->
        </table>
        </div>
        <script>
            //write script herei
            function showDate(appId)
            {

                document.getElementById("appId").innerHTML = Date();
            }
        </script>
    </body>
</html>

最佳答案

您不想在使用参数时用引号引起来:

function showDate(appId) {
    document.getElementById(appId).innerHTML = Date();
    // No quotes here ------^----^
}

关于JavaScript,将 id 作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32924356/

相关文章:

jquery - 如何在 jquery 中更改悬停菜单项的颜色?

php - jQuery Ajax 一旦没有更多结果

javascript - 为什么 x.push[0] 没有产生错误?

html - 无法在页面底部设置页脚

javascript - 我们如何在 javascript 函数表中给出选择选项

底部的 HTML CSS 页脚

javascript - 这是 Chrome 的错误吗?我该如何解决? : It skips some alert comments in the opener's Function

javascript - 使用 jQuery 在数据元素内定位对象

javascript - 将文本从弹出表单插入到 div 中,并用 javascript 重写插入的文本

html - 无法在 HTML5 中播放视频