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
createElement in javascript to set "onchange" attribute
提问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 onchange
property 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 onchange
to 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 this
keyword within your validation
function:
或者,如果您想要来自输入本身的信息,您可以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;
}