简体   繁体   English

编写 HTML 按钮以链接到 JavaScript 文件

[英]Code a HTML button to link to a JavaScript file

I'm trying to get a button written in HTML to link to a separate JavaScript file when it is clicked, the button in question is coded below我试图让一个用 HTML 编写的按钮在点击时链接到一个单独的 JavaScript 文件,有问题的按钮编码如下

<input type="button" id="clickme" value="Submit" />

I am using the Brackets code editor, and the js file I want to be linked is in the same project as my HTML code, if that helps at all我正在使用 Brackets 代码编辑器,我想链接的 js 文件与我的 HTML 代码在同一个项目中,如果这有帮助的话

thanks in advance提前致谢

Load the script into the page with a <script> element.使用<script>元素将脚本加载到页面中。

Keep your code in a function instead of simply running the whole thing with the script is loaded.将您的代码保存在一个函数中,而不是简单地在加载脚本的情况下运行整个事情。

Find the button in the DOM (eg with getElementById ) and bind the function as a click event listener with addEventListener ).在 DOM 中找到按钮(例如使用getElementById )并使用addEventListener将该函数绑定为单击事件侦听器。

If you mean link, I would use an <a> (anchor) tag which has an attribute href which is the reference.如果你的意思是链接,我会使用一个<a> (锚点)标签,它有一个属性href作为引用。 Therefore, you could use:因此,您可以使用:

<a href="http://example.com/public/js/script.js">Link to JS</a>

Or perhaps you meant the onclick attribute which would be: <input type="button" id="clickme" onclick="myfunction()" value="Submit" />或者你的意思是onclick属性是: <input type="button" id="clickme" onclick="myfunction()" value="Submit" />

However, as was pointed out, this is not best practice either.然而,正如所指出的,这也不是最佳实践。

jQuery.click() vs onClick jQuery.click() 与 onClick

Provides some options and reinforces the idea that onclick is not the best way to trigger a Javascript function.提供了一些选项并强化了onclick不是触发 Javascript 函数的最佳方式的想法。

Just link your js script to a page by:只需通过以下方式将您的 js 脚本链接到页面:

<script src="js/button.js"></script>

and then just call action in that scripts through the class or id.然后只需通过类或 ID 在该脚本中调用操作。

 <button id="btnShow"><h1 class="jumbotron-heading">Expand</h1></button>
 <p class="p1">Test</p1>

That's a jQuery not js, but anyway a good example as I think那是一个 jQuery 而不是 js,但无论如何都是我认为的一个很好的例子

$('#btnShow').click(function(){
 $('.p1').show();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM