使用 JavaScript 在不同的输入中获取时间

get time in different inputs with javascript

本文关键字:输入 获取 取时间 JavaScript 使用      更新时间:2023-09-26

我试图重用一个简单的函数,该函数打印单击按钮的时间。我为每个输入都有一个按钮。当我想更新时间时,我点击按钮。

好吧,我不知道如何将一个变量从HTML/PHP传递给Javascript,其中包括输入的ID,避免为每个输入创建相同的Javascript代码

如果我在 document.getElementById(( 行中写引号之间的输入名称,它可以工作,但我想使用一个变量。

对不起我的英语!

    <html>
      <head>
       <script type="text/javascript">
    function TellMeTime(input_selected)
    {var fecha = new Date();
        document.getElementById(input_selected).value = fecha.getFullYear() +'-' + fecha.getMonth() +'-'+ fecha.getDay() + ' ' + fecha.getHours() +':'+ fecha.getMinutes() +':'+ fecha.getSeconds();}
       </script>
      </head>
      <body>
       <form>
        <input type="button" onclick="TellMeTime(hello)" value="<- Hello">
        <input type="text" size="80" id="hello" name="hello" value="nothing yet"> 
        <br><hr>
            <input type="button" onclick="TellMeTime(bye)" value="<- Bye">
        <input type="text" size="80" id="bye" name="bye" value="nothing yet"> 
       </form>
      </body>
    </html>

你正在将一个字符串作为参数传递给Javascript中的函数。字符串用单'引号或双引号内的值表示"

在你的HTML中,你传递id字符串值作为你的参数。 你可以这样使用

onclick="TellMeTime('hello')" 
onclick="TellMeTime('bye')"

要将变量从 PHP 传递到 JavaScript,你只需要做这样的事情:

<?php
<script>
    // it's a string, so we use quotes
    var foo = '<?php echo $myVariable; ?>'
</script>