动态添加删除元素

点击按钮添加文字,点击文字后的删除,删除添加的内容

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script>
window.onload = function() {
    
    var oText = document.getElementById('text1');
    var oBtn = document.getElementById('btn');
    var oUl = document.getElementById('ul1');
    
    oBtn.onclick = function() {

        
        var oLi = document.createElement('li');
        
        //oLi.innerHTML = oText.value + '<a href="javascript:;">删除</a>';
        oLi.innerHTML = oText.value;
        
        var oA = document.createElement('a');
        oA.innerHTML = '删除';
        oA.href = 'javascript:;';
        oA.onclick = function() {
            
            oUl.removeChild( this.parentNode );
            
        }
        
        oLi.appendChild( oA );

        
        if ( oUl.children[0] ) {
            oUl.insertBefore( oLi, oUl.children[0] );
        } else {
            oUl.appendChild( oLi );
        }
        
    }
    
}
</script>
</head>

<body>
    <input type="text" id="text1" /><input type="button" value="留言" id="btn" />
    <ul id="ul1"></ul>
</body>
</html>

 

posted @ 2017-03-29 19:27  念念念不忘  阅读(144)  评论(0)    收藏  举报