js实现动态添加内容

27 篇文章 0 订阅

1.先来一段类似微博评论的代码:

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/weibo.css">
</head>

<body>
    <div class="w">
        <div class="controls">
            <!-- <img src="./assets/tip.png" alt=""><br> -->
            <textarea placeholder="说点什么吧..." id="area" cols="30" rows="10" maxlength="200"></textarea>
            <div>
                <span class="useCount">0</span>
                <span>/</span>
                <span>200</span>
                <button id="send">发布</button>
            </div>

        </div>
        <div class="contentList">
            <ul>
                <!-- <li>

                </li>  -->
            </ul>
        </div>
    </div>
    <script>
        // 获取
        let area = document.getElementById('area')
        let send = document.getElementById('send')
        let ul = document.querySelector('ul')
        let useCount = document.querySelector('.useCount')

        //    监听
        send.addEventListener('click', function () {
            // 创建
            // 如果用户啥都没有输入,则不执行
            if (area.value.length === 0) return
            let li = document.createElement('li')
            ul.appendChild(li)
            li.innerHTML = ` <div class="info">
      
              <span>用户名</span>
              <p>${new Date().toDateString()}</p>
          </div>
          <div class="content">
              ${area.value}
               <a href="javascript:;">删除</a>
          </div>`

            // 清除样式
            area.value = ''
            useCount.innerHTML = '0'


        })

        // 文本域的输入属性,输入多少字符就统计多少
        area.addEventListener('input', function () {
            useCount.innerHTML = area.value.length
        })

        // 委托
        ul.addEventListener('click', function (e) {
            if (e.target.nodeName === 'A') {
                ul.removeChild(e.target.parentNode.parentNode)
            }
        })
    </script>
</body>

</html>

看下效果:

2.再来一个例子:

<!DOCTYPE>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<!-- 动态添加与删除 -->
<script type="text/javascript">
 
    //创建函数
    function createButton() {
        //alert("获得");
        //创建新的 input按钮
        var all = document.createElement("input");
        //给元素添加属性
        all.type = "button";
        all.value = "确定";
        all.id = "did";
        //获得当前div并在div内部创建input
        document.getElementById("div1").appendChild(all);
    }
    /*删除按钮  */
    function deleteButton() {
        var ss = document.getElementById("did");
        document.getElementById("div1").removeChild(ss);
    }

    /* 获得链接 */
    function createLink() {
        //创建新的链接
        var ajj = document.createElement("a");
        ajj.href = "https://www.baidu.com/?tn=88093251_75_hao_pg";
        ajj.id = "ai";
        ajj.style.color = "red";
        //给a标签赋予名字
        ajj.innerText = "百度";
        //获取当前div并创建新链接
        document.getElementById("div1").appendChild(ajj);
    }

    //删除链接
    function deleteLink() {
        document.getElementById("div1").removeChild(document.getElementById("ai"));
    }

</script>

<body>
    <input type="button" value="增加按钮" onclick="createButton()">
    <input type="button" value="删除按钮" onclick="deleteButton()">
    <input type="button" value="增加链接" onclick="createLink()">
    <input type="button" value="删除链接" onclick="deleteLink()">
    <div style="width:300px;height:300px;border:1px  double  red;" id="div1">
        div
    </div>


</body>

</html>

 看下效果:

3.再来一个例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件委托
    </title>
</head>
<body>
    <div>
        <h4>购物车列表添加、删除</h4>
        <div>
            <label for="item.name">消费名称</label>
            <div>
                <input type="text" id="item-name" placeholder="输入购物名称">
                <button id="btn-add">添加</button>
            </div>
            <ul id="shopping-list">
                <!-- <li>
                    <p></p>
                    <button>删除</button>
                </li> -->
            </ul>
        </div>
    </div>
    <script>
        let btnAdd=document.querySelector('#btn-add')
        let itemName=document.querySelector('#item-name')
        let shoppingList=document.querySelector('#shopping-list')
        btnAdd.onclick=function(){
            shoppingList.insertAdjacentHTML('beforeend',`
            <li>
                    <p>${itemName.value}</p>
                    <button>删除</button>
                </li>
            `)
        }
        //事件委托
        shoppingList.onclick=function(e){
            if(e.target.tagName==='BUTTON'){
                e.target.parentNode.remove()
            }
            itemName.value=''
        }
    </script>
</body>
</html>

 看下效果:

4.我在项目里的运用:

点击+号tag时,要动态新增一个输入框,还有一个删除按钮

 

 代码如下:

   <!-- Attendant区域 -->
    <p class="choose-tag">Attendant</p>
    <div>
      <div class="attendant-area">
        <van-tag
          round
          color="#E7E7E7"
          text-color="#000"
          type="primary"
          @click="addAttendantFn"
          >+</van-tag
        >
        <span class="attendant-area-plus"> Add Attendant</span>
      </div>
      <ul id="add-row" @click="handleAttendantDetailDialog">
        <!-- 边框只显示底部线条 -->
        <!-- 这里时动态添加的内容 -->
      
      </ul>
    </div>

动态添加内容的代码如下:

   addAttendantFn() {
      console.log("点击增加操作框");
      let ul = document.getElementById("add-row");
      let li = document.createElement("li");
      ul.appendChild(li);

      li.innerHTML = `  <div style="width: 90%;  height: 32px;border: 1px solid #8e8e93; 
             margin-top: 17px;
             margin-left: 15px;
             border-radius: 10px;
             border-block-color: #8e8e93;">
            <span style="border-bottom: 1px solid #8e8e93; width: 44px; font-size: 15px;  margin-left: 6px;">Attendant</span>
            <span style="font-size: 13px;
              color: #8e8e93;
              margin-left: 10px;
              margin-right: 10px;">is a</span>
             <span style=" border-bottom: 1px solid #8e8e93;
             width: 44px;
             font-size: 15px;
             margin-left: 6px;
             color: #8e8e93;">Role</span>
            <span style="font-size: 13px;
            color: #8e8e93;
            margin-left: 10px;
            margin-right: 10px;">, works in</span>
            <span style="border-bottom: 1px solid #8e8e93;
             width: 44px;
             font-size: 15px;
             margin-left: 6px;
             color: #8e8e93;">Company</span><br>
           </div>

           <div>
             <a href="javascript:;" style="margin-left: 314px;
             color: red;
             font-size: 14px;">Delete</a>
           </div>
           
          `;
      // 委托
      ul.addEventListener("click", function (e) {
        if (e.target.nodeName === "A") {
          console.log("删除了");
          setTimeout(function () {
            console.log(e.target.parentNode.parentNode);
            //  ul.removeChild(e.target.parentNode.parentNode);
            ul.removeChild(e.target.parentNode.parentNode);
          }, 5);
        }
      });

      // this.showAttendant = true;
    },

其实,我个人在这里有疑惑的点是:我在动态添加内容的时候,其实样式已经丢失了,迫不得已我才使用了行内样式,有点突兀,目前我并没有探索到其他方法来解决样式丢失的问题。

而且还遇到的问题是,本来我点击Attendant会出现一个相关的控制面板,但是现在点击删除按钮的时候,虽然说删除功能可以实现,但是这个控制面板也弹出来了。

删除功能其实也有问题,当我动态新增两条内容时,点击第二条内容的删除时,控制台上给我报错了,虽然也删除了内容:

 控制台报的错是:

 虽然说删除了内容:

这两个事件委托发生了冲突,导致我删除的时候,已经删除了,但是触发了别的事件,节点已经不存在了,但是还触发了事件,因此报错了,我再细细研究一下,各位有什么好的想法,感激不尽!! 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值