簡體   English   中英

為什么我的JavaScript腳本在頁面加載時運行,而不與onclick一起運行?

[英]why is my javascript script running when the page loads and not with onclick?

因此,下面是單擊屏幕上的按鈕時要運行的腳本。 基本上使用AJAX來查詢我的數據庫獲取更多結果。 問題是,我是Java語言的新手,該腳本在頁面加載時運行,而不是在我單擊應該調用它的按鈕時運行。


<script type="text/javascript">
function next_ten_results()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("main").innerHTML=xmlhttp.responseText;
    }
  }
var page = "<?php echo $page_count; ?>";
alert('the city of ' + page + '!');
var name = "<?php echo $sql_name; ?>";
var rest_location = "<?php echo $sql_location; ?>";
xmlhttp.open("GET","another_ten_results.php?location="+rest_location+"&rest_name="+name+"&page="+page,true);
xmlhttp.send();
}
</script>  

感謝您的閱讀! 我確定我犯了一個簡單的錯誤,例如我需要等待文檔准備就緒等,但是正如我所說,我很新。 任何幫助和建議,不勝感激。

干杯!

編輯:在需要的情況下調用此函數的代碼...即使該代碼在沒有它的情況下運行:

if($num_rows > 9){
      echo '<onclick="next_ten_results_NOT()" class="button next" id="button_next" >Page 2</a>'; }

編輯(2):供以后參考,問題(如上所述,科迪)是我在onclick事件之前忘記了<a... 這是什么原因造成的代碼以某種方式運行。 更改后,javascript查詢按計划工作。 該錯誤實際上是在HTML中。

干杯!

對於那些訪問此網站尋找答案的人:

您的HTML調用javascript函數無效。 沒有以<onclick ...開頭的標簽。 我們可以通過結束標記</a>得知這應該是一個鏈接。

<onclick替換為<a onclick將解決此問題。

將我的答案移至答案,而不是原來的注釋:

您正在回顯'<onclick="next_ten_results_NOT()" class="button next" id="button_next" >Page 2</a>'; 這將創建一個名為的標簽。 您缺少<a ,這意味着它是無效的標記。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM