[英]How to Append a element with a remove function with it
I'm trying to append a list element with a remove function with it. 我正在尝试在列表元素上附加一个remove函数。 I already created the remove function and I can appended the element but have no idea how to append the element with the remove function with it. 我已经创建了remove函数,可以附加元素,但是不知道如何使用带有remove函数的元素来附加元素。
here's the code 这是代码
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#btn1").click(function () {
var listname = $('#listname').val();
$(".container").append($('<ol>', {
text: listname
}));
});
$("#btn2").on('click', function () {
var name = $('#name').val();
$('ol').append($('<li>', {
text: name
}));
});
$('ol').on('click', '.btn3', function () {
$(this).parent('li').remove();
});
});
</script>
<title></title>
</head>
<body>
<ol>
<li>List item 1 <button class="btn3">remove</button></li>
<li>List item 2 <button class="btn3">remove</button></li>
<li>List item 3 <button class="btn3">remove</button></li>
</ol>
<form>
<input id="name" type="text"> <button id="btn2">Append list items</button>
</form>
</body>
</html>
Tips, comments will be much appreciated 提示,评论将不胜感激
Try 尝试
$("#btn2").on('click', function () {
var name = $('#name').val();
$('<li>', {
text: name
}).appendTo('ol').append($('<button />', {
'class': 'btn3',
text: 'Remove'
}))
});
If the ol
is added dynamically then 如果ol
是动态添加的,则
$(document).on('click', 'ol .btn3', function () {
$(this).closest('li').remove();
});
create <li>
append <button>
to it.. and then append it to the <ol>
创建<li>
将<button>
<li>
附加到它..然后将其附加到<ol>
try this 尝试这个
$("#btn2").on('click',function(){
var name = $('#name').val();
var $li=$('<li>', { text: name}); //creating li element.
$li.append($('<button />',{text:"remove","class":"btn3"}).appendTo('ol');
//--^^^^^^^^^---- append created button to lu ---append li to ol
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.