[英]How do I make html run a javascript function when a user clicks a button?
I have a web form where users will type in a name of a person then click a button to open a page about that person. 我有一个Web表单,用户可以在其中键入一个人的姓名,然后单击一个按钮打开一个关于该人的页面。 eg They type Player One and it runs a function which opens the file C:\\PlayerOne.
例如,他们键入Player One,它运行一个打开文件C:\\ PlayerOne的函数。
I've tried using the <button>
tag and adding the onclick
element to run the function, but I was unable to diagnose the problem there either. 我尝试使用
<button>
标签并添加onclick
元素来运行该功能,但我也无法在那里诊断问题。 The Event Listener stuff I am not too familiar with, but I saw it [here] ( https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/button ) so I thought I'd try it that way instead. 事件监听器的东西我不太熟悉,但我看到了[这里]( https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/button )所以我想我我试试这种方式。
<form>
<fieldset>
<legend>Enter player name: </legend>
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname"><br><br>
<input type="button" value="Submit">
</fieldset>
<script>
const input = document.querySelector('button');
input.addEventListener('click', UseData);
function UseData()
{
var Fname=document.GetElementById('firstname');
var Lname=document.GetElementById('lastname');
window.location = "C:\" + Fname + Lname;
}
</script>
</form>
I want the user to be able to type the name and open the appropriate file, as explained above. 我希望用户能够键入名称并打开相应的文件,如上所述。 However, the button at this point simply does nothing.
但是,此时的按钮根本不起作用。 I do have a test file for it to reference, which I have been typing the name of in the fields of the form.
我有一个测试文件供它参考,我一直在表单的字段中输入名称。
It's because there's no button
tags in your form. 这是因为表单中没有
button
标签。 Use the attribute selector like so instead: 改为使用属性选择器:
const input = document.querySelector('input[type="button"]');
Here is an example of similar code by me involving a button triggering a function 这是我的类似代码的示例,涉及触发函数的按钮
The button: 按钮:
<button onclick="theFunction()">sampletext</button>
The script: 剧本:
var x = document.getElementById("sampleElement");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
In my example, the button is used to show/hide a div. 在我的示例中,该按钮用于显示/隐藏div。 Clicking my button triggers the function which changes the div visibility.
单击我的按钮会触发更改div可见性的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.