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

关于jQuery插件
刚看了jQuery插件的写法,于是练手写一个添加table的jQuery插件,大概是在匹配的元素内添加指定行数和列数的table,但失败了,贴出代码,望高人指点:
HTML code
<head runat="server">
    <title>无标题页</title>
    <script src="../JS/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="jquery.addtable.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            $("#kkk").addTable({row:2,line:3});
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="kkk">
    </div>
    </form>
</body>

JScript code
(function($) {
    $.fn.addTable = function(options) {
        var defaults = {
            row: 3,
            line: 3
        }
        var opts = $.extend(defaults, options);
        var tr = "<tr></tr>"; var td = "<td>日</td>"; var table = "<table></table>";
        for (var i = 0; i < opts.row; i++) {
            for (var j = 0; j < opts.line; j++) {
                $(tr).append($(td));
            }
            $(table).append($(tr));
        }
        $(this).append($(table));
    }
})(jQuery);


------解决方案--------------------

HTML code

<div  id="con">
</div>
<script type="text/javascript">
(function($) {
    $.fn.addTable = function(options) {
        var defaults = {
            row: 3,
            line: 3,
                        id:''
        }
        var opts = $.extend(defaults, options);
        var td = "<td>日</td>",arr=[];
                //如果要用jq创建table的话,这么写,最好还是都写成字符串push进arr,尽量少操作DOM
                var $table=$('<table/>');
        for (var i = 0; i < opts.row; i++) {
                        arr.push('<tr>')
            for (var j = 0; j < opts.line; j++) {
                arr.push(td)
            }
                        arr.push('</tr>')
        }
                $table.html($(arr.join('')))
                $('#'+defaults.id).append($table);
    }
})(jQuery);
$.fn.addTable({row:10,line:3,id:'con'});
</script>

------解决方案--------------------
楼上果然厉害,佩服