0

我有以下功能:

<script type="text/javascript">
        $(function(){
            // start a counter for new row IDs
            // by setting it to the number
            // of existing rows
            var newRowNum = 2;

            // bind a click event to the "Add" link
            $('#addnew').click(function() {
                // increment the counter
                newRowNum += 1;

                // get the entire "Add" row --
                // "this" refers to the clicked element
                // and "parent" moves the selection up
                // to the parent node in the DOM
                var addRow = $(this).parent().parent();

                // copy the entire row from the DOM
                // with "clone"
                var newRow = addRow.clone();

                // set the values of the inputs
                // in the "Add" row to empty strings
                //$('input', addRow).val('');
                //$('name', addRow).val('os' + newRowNum);

                // replace the HTML for the "Add" link 
                // with the new row number
                $('td:first-child', newRow).html('<input type="hidden" name="on' + newRowNum + '" value="Email Address ' + (newRowNum - 1) + '">Recipient');

                // insert a remove link in the last cell
                $('td:last-child', newRow).html('<a href="" class="remove">Remove<\/a>');

                // loop through the inputs in the new row
                // and update the ID and name attributes

                $('input:hidden', newRow).attr('id','on' + newRowNum ).attr('name','on' + newRowNum );
                $('input:text', newRow).attr('id','os' + newRowNum ).attr('name','os' + newRowNum );

                // insert the new row into the table
                // "before" the Add row
                addRow.before(newRow);
                document.tp01.quantity.value = newRowNum-1;
                // add the remove function to the new row
                $('a.remove', newRow).click(function(){
                    $(this).parent().parent().remove();
                    return false;               
                });

                // prevent the default click
                return false;
            });
        });

        </script>

通过单击表单中的链接调用此函数(此函数在表中添加或删除行)。链接如下所示:

<a id="addnew" href="">Add</a>

我需要在每个表单中的链接访问的同一页面上放置更多表单,就用户而言,这些表单与上面显示的完全相同。有人可以就我如何重用相同的功能来实现这一点提出建议吗?

谢谢

戴夫

4

1 回答 1

0

将嵌入的脚本移动到外部 JS 文件:

var newRowNum = 2;

var bindLink = function(linkSelector)
{
    // bind a click event to the "Add" link
    $(linkSelector).click(function() {
        ...
    }
}

然后在准备好的处理程序中调用 bindLink('#addnew') 代替嵌入式脚本。

于 2009-10-15T17:54:32.273 回答