hei*_*nst 3 html javascript if-statement button
我有这个代码:
<script type="text/javascript">
function changestate()
{
var StateTextBox = document.getElementById("State");
var IgnoreTextBox = document.getElementById("Ignore");
var PlayButton = document.getElementById("Play");
if(document.getElementById("Play").onclick == true)
{
StateTextBox.value = "Happy";
}
}
</script>
<input TYPE="button" VALUE="Play with Pogo" id="Play" onClick="changestate();"/>
Run Code Online (Sandbox Code Playgroud)
我试图知道何时单击该按钮,并在if语句中单击该按钮.我想知道这一点,所以我可以更改文本框内的值.问题是,我不知道如何判断单击按钮的时间.如果你能帮助我,那就太好了.
该onclick属性标识用户单击此特定元素时应发生的情况.在你的情况下,你要求运行一个函数; 当函数运行时,你可以放心点击按钮 - 这毕竟是函数本身如何启动(除非你以其他方式调用它).
你的代码有点令人困惑,但假设你有两个按钮,你想知道哪一个被点击,通过stateTextBox值通知用户:
(function () {
// Enables stricter rules for JavaScript
"use strict";
// Reference two buttons, and a textbox
var playButton = document.getElementById("play"),
stateTextBox = document.getElementById("state"),
ignoreButton = document.getElementById("ignore");
// Function that changes the value of our stateTextBox
function changeState(event) {
stateTextBox.value = event.target.id + " was clicked";
}
// Event handlers for when we click on a button
playButton.addEventListener("click", changeState, false);
ignoreButton.addEventListener("click", changeState, false);
}());
Run Code Online (Sandbox Code Playgroud)
您可以在http://jsfiddle.net/Y53LA/上测试此代码.
注意我们如何在我们的playButton和上添加事件监听器ignoreButton.这允许我们保持HTML清洁(不需要onclick属性).changeState当用户点击它们时,这两个都将触发该功能.
在changeState函数中,我们可以访问一个event对象.这为我们提供了有关发生的特定事件的详细信息(在本例中为click事件).该对象的一部分是target,被点击的元素.我们可以抓住id从元素属性,并将其放置到value的stateTextBox.
这是经过调整的HTML:
<input type="button" value="Play with Pogo" id="play" />
<input type="text" id="state" />
<input type="button" value="Ignore with Pogo" id="ignore" />?
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26692 次 |
| 最近记录: |