我试图在列表中的项目被选中时删除它们,然后单击“删除”按钮。我认为我的问题可能出在removeItem函数中。var x = document.getElementById("items-listed <li>");
因为当我删除<li>
整个列表时,也会删除。
<div>
<div id="center-container">
<h4>Enter an Item for Your Shopping List:</h4>
<hr />
<form name="form">
<label for="item">Item:</label>
<input type="text" placeholder="Shopping Items" id="item" name="itemEntered" />
<input type="button" value="Enter" id="Enter" onclick="javascript:addItem();" />
</form>
</div>
</div>
<div>
<div id="items-container">
<h4>Your list of Items:</h4>
<form>
<input type="button" value="Remove selected items" onclick="javascript:removeItem();" />
</form>
<hr />
<ul id="items-listed">
</ul>
</div>
</div>
function addItem() {
var item = [];
item = document.getElementById('items-listed');
item.innerHTML += "<li><input type='checkbox'>" + document.form.itemEntered.value + "</li>";
}
function removeItem () {
var x = document.getElementById("items-listed <li>");
x.remove();
}
一点帮助:http : //jsfiddle.net/wared/N3m65/。
<div>
<button onclick="add()">add</button>
<button onclick="rem()">rem</button>
</div>
<ul id="list">
<li><input type="checkbox" /> item</li>
</ul>
function add() {
var list = document.getElementById('list'),
item = document.createElement('li');
item.innerHTML = '<input type="checkbox" /> item';
list.appendChild(item);
}
function rem() {
var list = document.getElementById('list'),
items = Array.prototype.slice.call(list.childNodes),
item;
while (item = items.pop()) {
if (item.firstChild && item.firstChild.checked) {
list.removeChild(item);
}
}
}
这是一个jQuery解决方案:http : //jsfiddle.net/wared/N3m65/。
function jAdd() {
$('#list').append('<li><input type="checkbox" /> item</li>');
}
function jRem() {
$('#list').children().filter(function () {
return this.firstChild.checked;
}).remove();
}
正如BlackSheep建议的那样,您也可以这样做:
function jRem() {
$('#list li').has('input:checked').remove();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句