日期:2014-05-16  浏览次数:20361 次

onchange事件的回调函数如何传递参数
JScript code

function init(para1,para2){
   alert("aaa");
   var selectarr = document.getElementsByTagName("select");
   for (var i=0; i < selectarr.length;i++){
    var nm = selectarr[i].name;
    if (selectarr[i].options.length == 0) {
        selectarr[i].outerHTML="<input type='text' class='form1' name= '" + nm + "'  >";
        document.getElementsByName(nm)[0].onchange=new Function("changeCard("+para1+","+para2+")");
    }
   }
}
                
function changeCard(para1,para2){
    alert(para1.value)
    alert(para2.value)
}


其中init的参数是两个对象(document里的元素),我在传到changeCard的时候,总是报错:'object'未定义,请帮忙,谢谢!

------解决方案--------------------
document.getElementsByName(nm)[0].onchange=new Function("changeCard('"+para1+"','"+para2+"')");

------解决方案--------------------
JScript code

<script type="text/javascript">
function init(para1,para2){
    var selectarr = document.getElementsByTagName("select"), f = function () {
        changeCard(para1, para2);
    }, i = 0, nm;
    for (; i < selectarr.length ; i ++) {
        nm = selectarr[i].name, obj = selectarr[i];
        if (obj.options.length == 0) {
            obj.outerHTML = "<input type='text' class='form1' name= '" + nm + "'>";
            document.getElementsByName(nm)[0].onchange = f;
        }
    }
}
                
function changeCard(para1,para2){
    alert(para1.value)
    alert(para2.value)
}

window.onload = function () {
    var i = document.getElementsByTagName("input");
    init(i[0], i[1]);
};
</script>
<select name="se"></select>
<input value="a" />
<input value="b" />