繁体   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