2016-09-30 56 views
0

我得到了几分钟前写的代码我想知道为什么不会删除该项目。jQuery列表项删除

(function($) { 
 
    $('#btn1').click(function() { 
 
    var textVal = $('#input').val(); 
 
    if (textVal != "") { 
 
     $('#list').append('<li class="class1" id="' + textVal + '">' + textVal + '<input type="hidden" name="Tags" value="' + textVal + '" /> <input type="button" class="remove-item" value="X"></input></li> '); 
 
    } 
 
    }); 
 
    $('.remove-item').click(function() { 
 
    $('.list #' + textVal).remove() 
 
    }); 
 
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<input id="input" type="text" /> 
 
<input type="button" id="btn1" value="Add" /> 
 
<ul id="list"></ul>

+3

你需要的事件代表团在这里! –

回答

1

试试这个代码:

var textVal; 
 
    $('#btn1').click(function(){ 
 
    \t \t textVal = $('#input').val() 
 
     if (textVal != ""){ 
 
$('#list').append('<li class="class1" id="' + textVal + '">' + textVal + '<input type="hidden" name="Tags" value="' + textVal + '" /> <input type="button" class="remove-item" id='+textVal+' value="X"></input></li> '); 
 
      
 
    $('#'+ textVal +' .remove-item').click(function (e){ 
 
    $(e.target).parent().remove(); 
 
    }); 
 
      
 
     } 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="input" type="text" /> 
 
    <input type="button" id="btn1" value="Add" /> 
 

 
    <ul id="list"> 
 
    </ul>

此外,我会建议使用Backbone.js(基于MVC)这样的应用程序

0

请检查。目前li无需抓取text。相反,你可以搜索父li和如下可以将其删除:

(function($) { 
 
    $('#btn1').click(function() { 
 
    var textVal = $('#input').val() 
 
    if (textVal != "") { 
 
     $('#list').append('<li class="class1" id="' + textVal + '">' + textVal + '<input type="hidden" name="Tags" value="' + textVal + '" /> <input type="button" class="remove-item" value="X"></input></li> '); 
 
    } 
 
    }); 
 

 

 
    $("#list").on('click', '.remove-item', function() { 
 
    $(this).closest("li").remove() 
 

 
    }); 
 

 
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="input" type="text" /> 
 
<input type="button" id="btn1" value="Add" /> 
 

 
<ul id="list"> 
 
</ul>

1

您需要通过body添加.on(),并检查点击类是.remove-itemremove()它。

(function($) { 
 
    $('#btn1').click(function() { 
 
    var textVal = $('#input').val() 
 
    if (textVal != "") { 
 
     $('#list').append('<li class="class1" id="' + textVal + '">' + textVal + '<input type="hidden" name="Tags" value="' + textVal + '" /> <input type="button" class="remove-item" value="X"></input></li> '); 
 
    } 
 
    }); 
 
    $('body').on('click', '.remove-item', function(e) { 
 
    $(this).parent().remove() 
 
    }); 
 
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="input" type="text" /> 
 
<input type="button" id="btn1" value="Add" /> 
 

 
<ul id="list"> 
 
</ul>