添加一行NewRow

3 篇文章 0 订阅
1 篇文章 0 订阅

英语专八转前端,在家学习ing。
欲实现,为表格添加一行,内含两个单元格“hello””world”;
首先是布局代码,这里引入了boot;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>增加一行</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<table></table>
<script>
    window.onload=function () {
//        此处写代码
    }
</script>
</body>
</html>

假设没有表格的api,直接用js写,可以如下:

window.onload=function () {
    var el=function(){
        this.$=function(sel){
            var sel=document.querySelectorAll(sel);
            return sel.length===1?sel[0]:sel;
            //        这里需要改进,还没想好
        };
        this.newEl=function(el){
            return document.createElement(el)
        };
        this.frag=function(el){
            return document.createDocumentFragment().appendChild(this.newEl(el))
        };
        this.append=function (par,el){
            var par=this.$(par);
            var son=this.frag(el);
            par.appendChild(son)
        };
        this.content=function(el,content){
            var el=this.$(el);
            el.innerHTML=content;
        };
        this.addAttribute=function(el,attr,attrVal){
           this.$(el).setAttribute(attr,attrVal);
        }
    };
    var newtable=new el();
    newtable.append("table","tbody");
    newtable.addAttribute("table","class","table");
    newtable.append("tbody","tr");
    newtable.append("tr","td");
    newtable.addAttribute("td","class","bg-primary");
    newtable.content(".bg-primary","hello");
    newtable.append("tr","td");
    newtable.addAttribute("tr td:nth-child(2)","class","bg-success");
    newtable.content(".bg-success","world");
}

前端小白,吭哧吭哧出了这么多。
如果用用内置的api,则可能更快。以下是简单的代码;

 window.onload=function () {
//        此处写代码
        var table=document.querySelector("table");
        table.className="table";
        var row=table.insertRow();
        var td1=row.insertCell();
        td1.className="bg-primary";
        td1.innerHTML="hell";
        var td2=row.insertCell();
        td2.className="bg-success";
        td2.innerHTML="world";
    }

写的挺多,纯属无聊,如有调侃,欢迎井喷。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liugang0605

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值