【问题标题】:Unable to push checkbox values to array无法将复选框值推送到数组
【发布时间】:2018-09-04 13:02:21
【问题描述】:

无法打印字段值。抛出 "Cannot read property 'push' of undefined" 错误

我的组件.html

<div class="checkbox abc-checkbox abc-checkbox-success">
 <input class="inputChk" value="Serial_Number" id="ser_num" type="checkbox" checked="true">
 <label for="Serial_Number">Serial Number</label>
</div>
<div class="checkbox abc-checkbox abc-checkbox-success">
 <input class="inputChk" value="Stock_Number" id="stk_num" type="checkbox" checked="true">
 <label for="Stock_Number">Customer Stock Number</label>
</div>   
<button type="button" class="btn btn-primary" (click)="submitCheckedValues()">Submit</button>

我的组件.ts

export class Sample{
 fields: String[] = [];

 submitCheckedValues(){
    $('input:checkbox.inputChk').each(function ()  {
        var sThisVal = (this.checked ? $(this).val() : "");

        //printing sThisVal; 

        if(sThisVal){
            this.fields.push(sThisVal);
        }
    });
    console.log(this.fields);
}

【问题讨论】:

  • 我要确定的第一件事是函数内部的“this”就是你认为的那样。
  • $(this).val() 你的意思是?这是每次迭代的复选框值

标签: javascript angular typescript


【解决方案1】:

出现此错误是因为this.fields 未指向该类的fields 属性。 this 指的是匿名函数的作用域。

在执行代码之前需要将引用保存在局部变量中:

submitCheckedValues(){
    let self = this; // Store the reference

    $('input:checkbox.inputChk').each(function ()  {
        var sThisVal = (this.checked ? $(this).val() : "");

        //printing sThisVal; 

        if(sThisVal){
            self.fields.push(sThisVal); // Use the reference of self here
        }
    });

    console.log(this.fields);
}

【讨论】:

  • @Esco 点击复选标记将此问题标记为已接受的答案,如果它解决了您的问题,它会给回答者一些额外的业力。
  • 好的,我刚刚做了。我是新来的
【解决方案2】:

如果你想尝试,我想给另一个解决方案

 $.each([1, 2, 3], (function(i, e) {
    console.log(this);
 }).bind(this));

您可以将每个函数与 this 绑定,之后您可以在每个函数中访问 this。

【讨论】:

    猜你喜欢
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 2018-10-07
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多