1

我在下面有这个 javascript 和 php/html 代码:

<script>
          var examInput = document.getElementById('newAssessment').value;
          var dateInput = document.getElementById('newDate').value;
          var timeInput = document.getElementById('newTime').value;

         function showConfirm(){

         var confirmMsg=confirm("Are you sure you want to update the following:" + "\n" + "Exam: " + examInput +  "\n" + "Date: " + dateInput + "\n" + "Time: " + timeInput);

         if (confirmMsg==true)
         {
         submitform();   
     }
}

</script>

……

<?php

$editsession = "<form action=".htmlentities($_SERVER['PHP_SELF'])." method='post' id='updateForm'>

    <p><strong>New Assessment's Date/Start Time:</strong></p>
    <table>
    <tr>
    <th>Assessment:</th>
    <td><input type='text' id='newAssessment' name='Assessmentnew' readonly='readonly' value='' /> </td>
    </tr>
    <tr>
    <th>Date:</th> 
    <td><input type='text' id='newDate' name='Datenew' readonly='readonly' value='' /> </td>
    </tr>
    <tr>
    <th>Start Time:</th> 
    <td><input type='text' id='newTime' name='Timenew' readonly='readonly' value=''/><span class='timepicker_button_trigger'><img src='Images/clock.gif' alt='Choose Time' /></span> </td>
    </tr>
    </table>
    <div id='datetimeAlert'></div>


    </form>
";

echo $editsession;


?>

问题是在确认框中,它没有显示考试名称、日期和时间,这些都显示在 php/html 的文本框中。

例如它应该显示:

您确定要更新以下内容吗: 考试:DFRER 日期:20-02-2013 时间:16:00

相反,它显示:

您确定要更新以下内容吗: 考试:未定义 日期:未定义 时间:未定义

为什么是这样?

4

1 回答 1

0

<script>标签在标记中遇到时立即执行。我们假设您的<script>标签出现在它在getElementById()调用中引用的 HTML 之前。

由于设置变量的三行发生在任何函数之外,它们会立即执行,因此在加载 DOM 之前,相应的 DOM 元素还不存在并且变量变为undefined. 只需将它们移动到函数中即可。这具有额外的好处,即在您随后调用该函数时,这些值都是最新的。

 function showConfirm(){
   // Load these variables inside the function
   // If placed outside, their DOM nodes are not yet loaded when the script runs
   var examInput = document.getElementById('newAssessment').value;
   var dateInput = document.getElementById('newDate').value;
   var timeInput = document.getElementById('newTime').value;

   var confirmMsg=confirm("Are you sure you want to update the following:" + "\n" + "Exam: " + examInput +  "\n" + "Date: " + dateInput + "\n" + "Time: " + timeInput);

   if (confirmMsg)
   {
     submitform();   
   }
 }
于 2012-11-10T15:30:01.033 回答