我需要在 HTML 文件中拆分按钮,并将其单击 javascript 函数放入 javascript
文件中。
这是我迄今为止尝试过的:
试用一:结合HTML的submitbutton按钮和按钮的点击功能
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
</head>
<body>
<form id="advertiseForm" name="advertiseForm" method="post" >
<br /><br /><br />
<div style="text-align:center">
<input class="button button2" id="submitbutton" type="button" value="Submit" />
</div>
<script>
$( "#submitbutton" ).on( "click", validatelanded );
function validatelanded( event ){
alert( "Hello." );
}
</script>
</form>
</body>
试验2:将HTML文件中的HTML sumitbutton按钮及其点击功能分离到js文件中。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script type="text/javascript" src="advertisementlandedvalidationatclient.js"></script>
</head>
<body>
<form id="advertiseForm" name="advertiseForm" method="post" >
<br /><br /><br />
<div style="text-align:center">
<input class="button button2" id="submitbutton" type="button" value="Submit" />
</div>
</form>
</body>
广告landedvalidationatclient.js文件
<script type="text/javascript">
$( "#submitbutton" ).on( "click", validatelanded );
function validatelanded( event ){
alert( "Hello." );
}
</script>
试验 1 有效(我看到警报),试验 2 无效(我没有看到警报)。可能出了什么问题?
最佳答案
Trial 1 works ( I see alert) and Trial 2 does not work (I don't see alert). What could be wrong?
在第一次试验中,脚本位于 html 的底部。因此,当渲染 html 时,将解析脚本并绑定(bind)相应的事件处理程序。没关系,因为有一个具有指定 id 的按钮。
另一方面,在第二次试验中,您已将脚本加载到 html 的 head 标记中。此时js已解析完毕,没有任何按钮可以绑定(bind)该事件。 此外,没有必要使用 <script>
外部js文件中的标签。当我们在 html 文件中编写脚本时,我们会使用此标签。以下内容就足够了。
<script type="text/javascript" src="advertisementlandedvalidationatclient.js"></script>
如果你尝试这样做,那么问题就会解决:
$(function(){
$( "#submitbutton" ).on( "click", validatelanded );
function validatelanded( event ){
alert( "Hello." );
}
})
现在,当您的文档准备就绪时,换句话说,当您的 html 将由浏览器呈现时,您将绑定(bind)相应的事件处理程序。
顺便说一下,最好的做法是在 html 页面底部加载脚本。根据Progressive enhancement,这是一个很好的做法。 .
关于javascript - 如何将 HTML 按钮和 javascript 逻辑分离到不同的文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34565955/