gpt4 book ai didi

javascript - 如何判断按钮是否被点击

转载 作者:搜寻专家 更新时间:2023-10-31 22:32:21 25 4
gpt4 key购买 nike

我有这个代码:

<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();"/>

我试图知道按钮何时被点击,并在 if 语句中获取 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);
}());

您可以在 http://jsfiddle.net/Y53LA/ 上实时测试此代码.

请注意我们是如何在 playButtonignoreButton 上添加事件监听器的。这允许我们保持我们的 HTML 干净(不需要 onclick 属性)。只要用户点击它们,它们都会触发 changeState 函数。

changeState 函数中,我们可以访问 event 对象。这为我们提供了有关发生的特定事件(在本例中为 click 事件)的一些详细信息。此对象的一部分是 target,即被单击的元素。我们可以从该元素中获取 id 属性,并将其放入 stateTextBoxvalue 中。

这是调整后的 HTML:

<input type="button" value="Play with Pogo" id="play" />
<input type="text" id="state" />
<input type="button" value="Ignore with Pogo" id="ignore" />​

关于javascript - 如何判断按钮是否被点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13436778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com