Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法将复选框值推送到数组_Javascript_Angular_Typescript - Fatal编程技术网

Javascript 无法将复选框值推送到数组

Javascript 无法将复选框值推送到数组,javascript,angular,typescript,Javascript,Angular,Typescript,无法打印字段值。抛出“无法读取未定义的属性“push”错误 My component.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

无法打印字段值。抛出“无法读取未定义的属性“push”错误

My component.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>

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

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

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);
}

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

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

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);
}

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

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

你可以用它绑定每个函数,然后你可以在每个函数中访问它。

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

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

您可以用它绑定每个函数,然后您可以在每个函数中访问它。

我要确保的第一件事是,函数中的“this”就是您所认为的。$(this).val()您的意思是?这是每次迭代时的复选框值。我要确保的第一件事是,函数中的“this”是您认为的值。$(this).val()您的意思是?这是每个位置的复选框值iteration@Esco单击复选标记,将此问题标记为已接受的答案。如果它解决了您的问题,则会给回答者带来额外的业力。好的,我刚刚做了。我是新来的here@Esco单击复选标记,将此问题标记为已接受的答案。如果它解决了您的问题,则会给回答者带来额外的业力。好的,我刚刚做了。我是新来的