从同一页面上的多个表单访问功能

时间:2009-10-15 17:49:15

标签: function reusability

我有以下功能:

<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>

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

由于

戴夫

1 个答案:

答案 0 :(得分:0)

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

var newRowNum = 2;

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

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