JS如何添加行和删除行?

JS如何添加行和删除行?,第1张

<!DOCTYPE html>

<html lang="">

<head>

<meta charset="gb2312">

<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">

<title>123</title>

<script src="Scripts/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript">

$(document).ready(function(){

var spotMax = 30

if($('div.spot').size() >= spotMax) {$(obj).hide()}

$("input#add").click(function(){     addSpot(this, spotMax)

})

})

function addSpot(obj, sm) {

$('div#spots').append(

'<div>' +

'<span><input name="shengfen" type="text" /></span>'+

'<span><input name="diqu" type="text" /></span>'+

'<input type="button" class="remove spot01" value="删除行" /></div>')

.find("input.remove").click(function(){

$(this).parent().remove()

$('input#add').show()

})

if($('div.spot').size() >= sm) {$(obj).hide()}

}

</script>

</head>

<body>

<span><input name="shengfen" type="text" /></span>

<span><input name="diqu" type="text" /></span>

<input type="submit" id="add" name="Submit" value="添加行" >

<div>

<form method="post" name="asdf" id="asdf"><div id="spots"></div></form>

</div>

</body>

</html>

效果这样(样式再自己调)

要加jQuery插件进去

不懂再追问

function appendTable(jsonObj) {

    var tabL = gel("tbList")

    var taRow = tabL.rows //tabL 对象的行集合

 

    //这里应该是判断有几行,取 length

    if (taRow.length > 1) { //原先是不满足条件,而不是删除不起作用

        tabL.deleteRow(2)

    }

    for (i = 0 i < jsonObj.length i++) {

        //...

        //如果你的 ID 不是纯数字的话,要用下面的写法

        nCol6.innerHTML = "<a href=\"javascript:doDel('" + jsonObj[i].ID + "')\">删</a>&nbsp..."

    }

}

window.onload = function () {

    const params = document.getElementById('params')

    const ul = params.querySelector('ul')

    const addBtn = ul.querySelector('#add')

    addBtn.onclick = function (e) {

        const newli = document.createElement('li')

        newli.appendChild(document.createElement('input'))

        const btn = document.createElement('input')

        btn.setAttribute('type', 'button')

        btn.setAttribute('value', '删除')

        btn.setAttribute('opt-type', 'del')

        newli.appendChild(btn)

        ul.appendChild(newli)

    }

    ul.onclick = function (e) {

        const target = e.target

        const optType = target.getAttribute('opt-type')

        if (target.nodeName === 'INPUT' && target.type === 'button' && optType === 'del') {

            this.removeChild(target.parentNode)

        }

    }

} <div id="params">

    <ul>

        <li><input type="text"><input id="add" type="button" value="添加一行"></li>

    </ul>

</div>

点击"添加一行",生成一条li,包含input,然后append进ul里边。点击删除,用ul删除按钮父元素li。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11844466.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存