在javascript中创建元素以设置“onchange”属性 [英] createElement in javascript to set "onchange" attribute

查看:96
本文介绍了在javascript中创建元素以设置“onchange”属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var f = document.getElementById 

我试图动态地添加一个新的输入字段(dN [+ fieldsd +]); //创建/插入新
el = document.createElement(input);
el = f.appendChild(el);
el.name =dName [+ fieldsd +];
el.id =dName [+ fieldsd +];
el.onchange =validation();

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

解决方案

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

  var f = document。 getElementById(dN [+ fieldsd +]); //创建/插入新
el = document.createElement(input);
el = f.appendChild(el);
el.name =dName [+ fieldsd +];
el.id =dName [+ fieldsd +];
el.onchange =验证;

(你有一个名为 validation



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

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

或者,如果您需要来自输入本身的信息,则可以使用 验证函数中的关键字:

  el.onchange =验证; 

....

函数验证(){
//这是函数的上下文。在这种情况下
//改变的元素。
var value = this.value;

}


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

    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?

解决方案

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

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)

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

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:

el.onchange = validation;

....

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

}

这篇关于在javascript中创建元素以设置“onchange”属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆