我想在javascript中创建一个简单的切换按钮 [英] I am trying to make a simple toggle button in javascript

查看:72
本文介绍了我想在javascript中创建一个简单的切换按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在javascript中创建一个简单的切换按钮。但是,该按钮只会变为OFF并且不会ON返回

I am trying to make a simple toggle button in javascript. However, the button will only turn "OFF" and will not turn back "ON"

<html><head></head>
<script type="text/javascript">
function toggle(button)
{
  if(document.getElementById("1").value=="OFF"){
   document.getElementById("1").value="ON";}

  if(document.getElementById("1").value=="ON"){
   document.getElementById("1").value="OFF";}
}
</script>
<body>
<form action="">
<input type="button" id="1" value="ON" style="color:blue"
       onclick="toggle(this);">
</form></body></html>

我正在运行:HP Netbook:Ubuntu Linux 10.04:Firefox for Ubuntu 1.0。

I am running:HP Netbook : Ubuntu Linux 10.04 : Firefox for Ubuntu 1.0.

推荐答案

当您更改时,两个 if 语句都会一个接一个地执行价值,然后立即再次阅读并将其更改回来:

Both of your if statements are getting executed one after each other, as you change the value and then immediately read it again and change it back:

function toggle(button)
{
  if(document.getElementById("1").value=="OFF"){
   document.getElementById("1").value="ON";}

  else if(document.getElementById("1").value=="ON"){
   document.getElementById("1").value="OFF";}
}

在那里添加 else 应该可以阻止这种情况发生。

Adding the else in there should stop this happening.

这篇关于我想在javascript中创建一个简单的切换按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆