通过比较删除列表

时间:2015-11-06 19:42:04

标签: javascript jquery html

<html>
<head>
<title>
Adding/Removing list item to/from list with JavaScript
</title>

<script type="text/javascript">
function appendNewNode(){
    if(!document.getElementById) return;

    var newlisttext = document.changeform.newlist.value;  //getting text from textfield

    var mylist=document.getElementById("mylist");

    var newlistitem=document.createElement("li");   //creating new element node <li>
    var newlistitemtext=document.createTextNode(newlisttext); //creating text node with text retrieved from textfield
    newlistitem.appendChild(newlistitemtext);   //Inserting text to <li>    

    mylist.appendChild(newlistitem);    //appending <li> to <ul>

    document.changeform.newlist.value="";   //setting textfield value to blank
    document.changeform.newlist.focus();    //setting focus to textfield
}

function removeNode(){
    mylist.removeChild(mylist.lastChild);
}
</script>
</head>

<body>

    <ul id='mylist'>
        <li>First</li>
        <li>Second</li>
    </ul>


    <form name="changeform">
        <input type="text" name="newlist"  size="65">
        <input type="button" onclick="appendNewNode();" value="Append To List">


        <input type="button" onclick="removeNode();" value="Remove from List">
    </form>
</body>
</html>

此代码添加新列表单击添加列表按钮但我想在文本框中输入相同文本后删除列表并按删除仅删除该列表

示例假设我要删除列表第二,所以我将在新列表文本框中输入“Second”并按删除按钮仅删除该列表

2 个答案:

答案 0 :(得分:0)

function removeNode(){
var newlisttext = document.changeform.newlist.value;
var mylist=document.getElementById("mylist");
var listItems = mylist.getElementsByTagName('li');  
for(var i = 0; i < listItems.length; i++) {
    var elem = listItems[i];
    if (newlisttext === elem.innerText) {
        elem.parentNode.removeChild(elem);
    }
}
}

答案 1 :(得分:0)

function removeNode(){
        var newlisttext = document.changeform.newlist.value;
        if(newlisttext ==''){alert('Please Enter List Name to Delete!');}
        var mylist=document.getElementById("mylist");
        var listItems = mylist.getElementsByTagName('li');  
        for(var i = 0; i < listItems.length; i++) {
            var elem = listItems[i];
            if (newlisttext === elem.innerHTML) {
                elem.parentNode.removeChild(elem);
            }else{alert('This list is not found !');}
        }
}

警报无法正常工作。