如何获得ON / OFF开关的值

时间:2019-06-25 12:50:10

标签: javascript angular web

我的网络项目中有开/关切换器:

HTML:

<div  class="onoffswitch">
   <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" 
    id="myonoffswitch" checked>
   <label class="onoffswitch-label" for="myonoffswitch">
     <span #onoffswitch class="onoffswitch-inner"></span>
     <span class="onoffswitch-switch"></span>
   </label>
</div>

CSS:

.onoffswitch-inner:before {
    content: "ON";
    padding-left: 10px;
    background-color: #93297E; color: #FFFFFF;
}

.onoffswitch-inner:after {
    content: "OFF";
    padding-right: 10px;
    background-color: #EEEEEE; color: #999999;
    text-align: right;
}

我想知道切换器是打开还是关闭,我尝试使用下一个代码获取该值,但是它不起作用:

getSwitcherValue(onoffswitch) {
   console.log("onoffswitch:"+onoffswitch.style.content);
}

您对如何获得开/关切换器的价值有任何想法吗?

5 个答案:

答案 0 :(得分:0)

使用onoffswitch.checked代替onoffswitch.style.content

答案 1 :(得分:0)

更改为:

    <div  class="onoffswitch">
   <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" 
    id="myonoffswitch" [(ngModel)]="isChecked">
   <label class="onoffswitch-label" for="myonoffswitch">
     <span #onoffswitch class="onoffswitch-inner"></span>
     <span class="onoffswitch-switch"></span>
   </label>
</div>

并将isChecked作为布尔值添加到ts文件中。

答案 2 :(得分:0)

您正在使用Angular。因此,请使用NgModel

<div  class="onoffswitch">
   <input type="checkbox" [(ngModel)]="onOff" name="onoffswitch" class="onoffswitch-checkbox" 
    id="myonoffswitch" checked>
   <label class="onoffswitch-label" for="myonoffswitch">
     <span #onoffswitch class="onoffswitch-inner"></span>
     <span class="onoffswitch-switch"></span>
   </label>
</div>

在您的TS文件中:

public onOff = false;

您现在只需检查this.onOff即可查看您的开关是否“打开”。

答案 3 :(得分:0)

如果您使用的是角度,只需使用其称为双向绑定的功能

Ref:https://angular.io/api/forms/NgModel

您的问题解决方案:

https://stackblitz.com/edit/angular-wcaqhb

答案 4 :(得分:0)

您可以尝试此解决方案

HTML文件(例如app.component.html)

<div  class="onoffswitch">
   <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" 
    id="myonoffswitch" [checked]="isSwitched"
  (change)="getSwitcherValue(isSwitched)">
   <label class="onoffswitch-label" for="myonoffswitch">
     <span #onoffswitch class="onoffswitch-inner"></span>
     <span class="onoffswitch-switch"></span>
   </label>
</div>

Ts文件(app.component.ts)

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  isSwitched:boolean=true;
  getSwitcherValue(onoffswitch) {
    this.isSwitched=!this.isSwitched;
   console.log("onoffswitch:"+this.isSwitched);
}
}

Css文件(app.component.css)

.onoffswitch-inner:before {
    content: "ON";
    padding-left: 10px;
    background-color: #93297E; color: #FFFFFF;
}

.onoffswitch-inner:after {
    content: "OFF";
    padding-right: 10px;
    background-color: #EEEEEE; color: #999999;
    text-align: right;
}

这里是Demo链接以供参考