2016-09-30 51 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>