在HTML和JQuery中切换按钮

Toggle button in HTML and JQuery

本文关键字:按钮 JQuery HTML      更新时间:2023-09-26

我正在尝试使用以下方法创建一个切换按钮,但它不起作用。我已经包含了我正在使用的CSS,HTML和JavaScript片段。如果我做得不对,请指教。

.CSS:

.toggle-button {
  margin-bottom: 15px;
}
.toggle-button img {
  display:    inline-block;
  height:     30px;
  width:      60px;
  background: url(../images/on-button.png) no-repeat center center;
}
.toggle-button img.down {
  background: url(../images/off-button.png) no-repeat center center;
} 

.HTML:

 <head>
 <script Language="JavaScript">
     function toggle (img) {  
         $(img).toggleClass("down");
     }
 </script>
 </head>
 <div class="right-form">
     <h2>Email Settings</h2>
     <div class="toggle-button">
         <label>Stock Require Scanning:</label>
         <img ondblclick="toggle(this);" border="0 id="stock_require_scanning"/>
     </div>                    
     <div value="OFF" class="toggle-button">
         <label>Head Office Alerts:</label>
         <img ondblclick="toggle(this);" class="down" border="0" id="head_office_alerts"/>
     </div>                                    
 </div>

我有什么地方做得不对吗?

这里有一个正在运行的演示:http://jsfiddle.net/L9nHY/(我用绿色表示"on",红色表示"down")。你在这里犯了一个错误:

<img ondblclick="toggle(this);" border="0"    id="stock_require_scanning"/>

您必须将this替换为'#stock_require_scanning'

<img ondblclick="toggle('#stock_require_scanning');" border="0"    id="stock_require_scanning"/>

您必须对另一个按钮执行相同的操作。

编辑: Sree: 另请参阅此: http://jsfiddle.net/L9nHY/1/