簡體   English   中英

如何在HTML中加載JavaScript onclick?

[英]How do I load a JavaScript onclick in HTML?

這個問題與我創建的音樂發現工具有關。 夢幻FM

在div元素中,我有一個JavaScript,可從數組中隨機選擇一些HTML。 然后將隨機選擇的HTML寫入我的文檔(索引)。 數組中的每個數字都是寫入HTML的不同歌曲。 轉到下一首新歌的唯一方法是當前刷新頁面。 我想加載按鈕的JavaScript onclick,而不必重新加載頁面以獲取下一首歌曲。

目前,我正在使用此方法重新加載外部JavaScript:

<button id="nextbtn" type="button" onclick="shuffle()" autofocus>></button>

<script>
function shuffle() {
location.reload(true); 
}
</script>

我只想加載JavaScript,而不重新加載整個頁面。

不要編寫代碼/不要用html內聯實現JS文件。 將代碼包裝在一個函數中,然后根據需要調用它。 Onload或Onclick:

function displayRandomSong(){
// put all of Your current code here if there is no function and
// every thing is pure javascript codes. I think this meets your need.

// However if your JS file is a complex of many functions, There is always 
// a function Which is triggered before others. Call that function here
// For example:
// startRandomization()
 }

因此,HTML將是這樣的:

<a onclick="displayRandomSong()">inline refresh</a>

暫無
暫無

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

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