我无法修改克隆javascript的对象的onchange字段

时间:2015-12-14 17:23:45

标签: javascript html function onchange getelementbyid

我在编辑html onchange属性时遇到问题,不允许我这样做。我的代码HTML是:

<table id="insertar">
                <tr><td>Producto</td><td>Stock</td><td>Cantidad</td></tr>
                <tr><td>
                <select id="p1" name="producto[]" onChange="document.getElementById('stock1').value = setStock('p1')" >
        <option value="" >---------</option>
                <option value="Mexico">Mexico</option>
                </select>
                </td>
                <td><input type="text" id="stock1" value="" name="stock[]" readonly /></td>
                <td><input type='text' name='cantidad[]' required /></td></tr>
            </table>
      <a href="#" onclick="addRow()" >Agregar otro</a>

我的代码Javascript是:

var _default;
var counter=2;
window.onload=function(){
    var x=document.getElementById("insertar").tBodies[0];
    _default =x.rows[1].cloneNode(true);  
}
function addRow(){
    var c=0;
    var x=document.getElementById("insertar").tBodies[0];
    Array.prototype.slice.call(_default.childNodes, 0).forEach(function(value){
        Array.prototype.slice.call(value.childNodes, 0).forEach(function(value1){
            if((value1.nodeType === 1) && (c === 0)){
                value1.id="p" + counter;
value1.onchange="document.getElementById(\"stock"+counter+"\").value = setStock(\"p"+counter+"\")";
                c++;
            }else if((value1.nodeType === 1) && (c === 1)){
                value1.id = "stock" + counter;
                c++;
            }
        });  
    });  
    counter++;
    x.appendChild(_default.cloneNode(true));
}

如果我工作正常,只是我无法更改onchange上的值

1 个答案:

答案 0 :(得分:0)

I find my answer. I use:

function addRow(){
    var c=0;
    var x=document.getElementById("insertar").tBodies[0];
    Array.prototype.slice.call(_default.childNodes, 0).forEach(function(value){
        Array.prototype.slice.call(value.childNodes, 0).forEach(function(value1){
            if((value1.nodeType === 1) && (c === 0)){
                value1.id="p" + counter;
                value1.setAttribute("onchange","document.getElementById('stock"+counter+"').value = setStock(this.id)");
                c++;
            }else if((value1.nodeType === 1) && (c === 1)){
                value1.id = "stock" + counter;
                c++;
            }
        });  
    });  
    counter++;
    x.appendChild(_default.cloneNode(true));
}