Javascript:如何获取改变输入的值

Javascript: how to get the value of a changing input

本文关键字:改变 输入 获取 何获取 Javascript      更新时间:2023-09-26

我有这个代码,但我不能得到输入到helpCallback()的值,所有我得到的是未定义的。我必须用闭包来做。

function tablaR(num){
    var seccion=document.getElementById("tabla");
    seccion.innerHTML="";
    seccion.style.display='block';
    for (var i = 0; i < 11; i++) {
        var prod=parseInt(num*i);
        var t=document.createTextNode(num+" x "+i+"= ");
        var inp=document.createElement('INPUT');
        inp.setAttribute('type', 'number');
        inp.setAttribute('id', 'resul');
        inp.addEventListener("change", helpCallback(num, this.value));
        var para=document.createElement("p");
        para.appendChild(t);
        para.appendChild(inp);
        seccion.appendChild(para);
    }
}
function helpCallback(prod, resp){
    return function(){
        resp=parseInt(inp.value);
        if(resp!=prod){
            this.style.color = "red";
        }
        else{
            this.style.color = "green";
        }
    }
}

this不是执行helpCallback函数的元素,但您可以直接获取返回函数中的值

inp.addEventListener("change", helpCallback(num));
function helpCallback(prod){
    return function(){
        var resp = parseInt(this.value, 10);
        if(resp!=prod){
            this.style.color = "red";
        } else{
            this.style.color = "green";
        }
    }
}