[英]How to make JavaScript work when button is pressed?
I am a bit of a newbie in JS and not too sure what I'm doing. 我是JS的新手,不太确定自己在做什么。
I have created a button 我创建了一个按钮
<div id="btn">
<a href='dg-quiz-maker.js' class='button'>ATTEMPT A QUIZ</a>
</div>
I want when the user presses the button, the JS dg-quiz-makes.js file appears. 我想要当用户按下按钮时,出现JS dg-quiz-makes.js文件。 I'm not sure how to I do it.
我不确定该怎么做。 Please help.
请帮忙。
Steps to add a event : 添加事件的步骤:
1).Add selector (either class or id) to the element (ex: <--button class="classname">test<--/button-->) 1)。向元素添加选择器(类或ID)(例如:<-button class =“ classname”> test <-/ button->)
2).In document ready - Add on click event and write the related code inside it. 2)。准备好文档-点击事件添加并在其中写入相关代码。
Note : Add Jquery.js in HTML page 注意:在HTML页面中添加Jquery.js
$( document ).ready(function() { $('.classname').on('click',function(){ /** write related code inside **/ yourfunc(); }); }); function yourfunc(){ alert('this is the other function'); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="classname">test</button>
What you can do is make a javascript function and call it on click like this: 您可以做的是制作一个javascript函数,并在单击时调用它,如下所示:
<div id="btn">
<a href='#' onclick="myFunc();" class='button'>ATTEMPT A QUIZ</a>
</div>
<script>
function myFunc(){
alert('test');
}
</script>
Or you can include functions from js files like this: 或者,您可以像这样从js文件中包含函数:
<script src="dg-quiz-maker.js"></script>
you just cant use .click() as some browser wont pick it up. 您不能使用.click(),因为某些浏览器不会选择它。 please test after using .
使用后请进行测试。
<script type="text/javascript">
function performClick(elemId) {
var elem = document.getElementById(elemId);
if(elem && document.createEvent) {
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, false);
elem.dispatchEvent(evt);
}
}
</script>
<a href="#" onclick="performClick('theFile');">Open file dialog</a>
<input type="file" id="theFile" />
<div id="btn">
<a href='dg-quiz-maker.js' class='button'>ATTEMPT A QUIZ</a>
</div>
See the Plunker code: 请参阅柱塞代码:
http://plnkr.co/edit/YB09Puxc7qJmeW8V86nR?p=preview ` http://plnkr.co/edit/YB09Puxc7qJmeW8V86nR?p= preview`
In this case the script file is in same directory with HTML 在这种情况下,脚本文件与HTML位于同一目录中
First of All, Opening a JS file is kind of weird thing , but still if u want to,The " href
" property of <a>
tag should be a proper(or relative) uri path of the file placed in your directory. 首先,打开JS文件是一件很奇怪的事情,但是如果您愿意,
<a>
标签的“ href
”属性应该是放置在目录中文件的正确(或相对) uri路径 。
I hope it will solve your purpose. 我希望它能解决您的目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.