javascript javascript中的createElement设置“onchange”属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15341512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:27:37  来源:igfitidea点击:

createElement in javascript to set "onchange" attribute

javascripthtml

提问by user1647308

I am trying to dynamically add a new input feild with the "onchange" attribute:

我正在尝试使用“onchange”属性动态添加一个新的输入字段:

    var f = document.getElementById("dN[" + fieldsd + "]"); // create/insert new
    el = document.createElement("input");
    el = f.appendChild(el);
    el.name = "dName[" + fieldsd + "]";
    el.id = "dName[" + fieldsd + "]";
    el.onchange =  "validation()";

I have also tried setAttribute both don't work for me. Is there a way to make this work or a work around?

我也试过 setAttribute 都不适合我。有没有办法使这项工作或解决方法?

回答by scott.korin

In JavaScript, set the onchangeproperty to be a pointer to a function, not an actual string:

在 JavaScript 中,将onchange属性设置为指向函数的指针,而不是实际的字符串:

var f = document.getElementById("dN[" + fieldsd + "]"); // create/insert new
el = document.createElement("input");
el = f.appendChild(el);
el.name = "dName[" + fieldsd + "]";
el.id = "dName[" + fieldsd + "]";
el.onchange =  validation;

(Where you have a function named validation)

(你有一个名为 的函数validation

If you need to pass parameters, set onchangeto a function that calls the validation function:

如果需要传递参数,设置onchange为调用验证函数的函数:

el.onchange = function () {  
    validation(param1, param2, ...);
};

Or, if you want information from the input itself, you can use the thiskeyword within your validationfunction:

或者,如果您想要来自输入本身的信息,您可以this在您的validation函数中使用关键字:

el.onchange = validation;

....

function validation() {
    // this is the "context" for the function.  In this case
    // the element that changed.
    var value = this.value;

}