如何通过一些更改在同一元素中追加元素的子元素

时间:2013-12-31 05:52:58

标签: javascript php html

我有以下HTML代码

<button id="button_id" class="scalable add" title="Add email" type="button" onclick="emailsControl.addItem()" style="">
<tbody id="email_chain_container">
    <tr>
        <td class="nobr">
            <input type="file" id="chain_Image_1"  name="Image[1]" class="input-text" />
        </td>
        <td class="last"><input type="hidden"  class="delete" name="email_chain[delete][]" />
            <button onclick="emailsControl.deleteItem(event);return false" class="scalable delete icon-btn delete-product-option" title="Delete Image"><span><?php echo $this->__('Delete')?></span>   
            </button>
        </td>
    </tr>
</tbody>

当单击按钮时,我想获取tbody中的元素并将input元素中的索引更改为index + 1,然后将该元素再次附加到tbody。这是我用过的粗略代码。但是它不起作用

emailsControl = {
    addItem: function ()
    {
        var chainParent = document.getElementById('email_chain_container');
        var index = chainParent.childNodes.length; //get the number of tr elements present in tbody
        var repeat = chainParent.innerHTML;
        var newHTML = repeat.replace(index, (index + 1)).
        replace('Image[' + (index) + ']', 'Image[' + (index + 1) + ']');
        document.chainParent.appendChild(newHTML);
    },
}

如何以最有效的方式完成?请提出您的想法。提前致谢

1 个答案:

答案 0 :(得分:0)

最后我做到了。不知道这是否是最好的方法。但它确实有效!!!

<script type="text/javascipt">
emailsControl = 
{
     addItem : function () 
     {
         var chainParent = document.getElementById( 'email_chain_container' );
         var trElements = chainParent . getElementsByTagName("tr");
         var index = trElements . length;
         var childElements = trElements[0] . innerHTML;
         var newHTML = childElements . replace( /1/g , (index+1))
         var tr = document . createElement('tr');
         tr . innerHTML = newHTML;
         chainParent . appendChild (tr);        

   },
}
</script>