提问者:小点点

从HTML“onclick”运行外部Javascript函数[重复]


尽管有几个其他的解决方案,我还没有找到一个真正解决我的问题。我有一个HTML文件,其中包含一个带有

    <script type="text/javascript" src="./js/throwaway.js"></script>

在身体里有一个按钮,像这样:

    <button onclick="basicAlert()"></button>

并且我有Javascript函数basicAlert():

    function basicAlert() {
        alert("this is a test to see if basicAlert runs");
    }

我已经花了两天时间在这个问题上了,但是我不能让onclick函数在外部文件中执行basicAlert()。我可以在持有函数的HTML中有一个脚本,它将完美无瑕地运行,但当函数在外部文件中时,它就不运行了。尝试的解决方案包括尝试onsubmit(它是一个搜索栏),删除'type=“text/javascript”‘(因为默认的是JS),并将脚本src移动到文件的不同部分,头、正文、末尾等。使路径类似于“/JS/throwaway.JS”、“../JS/throwaway”,我认为每一种组合都是有意义的。当前的文件设置是一个节点app.js,它引用了包含HTML文档的文件夹public和包含throwaway程序的文件夹“js”。是的,文件位置相对于被引用的HTML是正确的。如果我可以把函数放在HTML里面,我会的,但是会有几个函数,所以我不想把HTML文件弄得乱七八糟。

我对javascript和HTML非常陌生,因此我将非常感谢任何帮助。提前道谢。

编辑:有人要求提供完整的相关代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Spotlight</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="css/style.css">
    <script type="text/javascript" src="./js/spotifyFunctions.js"></script>
</head>
<body>
<input type="text" class="form-control" id="songSearch" placeholder="Enter Song or Playlist...">
<button id="search" onclick="basicAlert()"><div class="search-icon"><ion-icon name="search"></ion-icon></div></button>
    <script src="link"></script> <!-- There's about 20 of these before the basic alert -->
    <script>
        function basicAlert() {
            alert("throwaway");
        }
    </script>
</body>
</html>

编辑2:我所拥有的Javascript文件可能是由于它的导入而导致的错误的罪魁祸首,感谢那些在这里帮助我的人

import Spotify from "spotify-web-api-js";
const spotifyApi = new Spotify();

//Several functions utilizing spotify API

function basicAlert() {
    alert("this is a test to see if basicAlert runs");
}
console.log("made it");

在控制台中抛出错误:

SyntaxError: import declarations may only appear at top level of a module

我自己也能搞清楚这件事。谢谢!


共2个答案

匿名用户

激发事件的最简单方法是在JS中添加事件侦听器

  • 给按钮一个ID
  • 在JS中按ID获取元素
  • 添加click事件侦听器

null

   function basicAlert() {
        alert("this is a test to see if basicAlert runs");
    }

// get the DOM element with JS

let bttn = document.getElementById("MyId");
bttn.addEventListener("click", basicAlert, false);
    <button id="MyId">CLick Me</button>


 

匿名用户

共享您的html代码。我高度怀疑您在HTML中犯了一些错误。如果您编写了如下代码,它应该可以工作:

null

function basicAlert() {
	alert('Throw away!');
}
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
	<button onclick="basicAlert()">Button</button>
	<script src="./js/throwaway.js"></script>
</body>
</html>

相关问题