jquery 将 li 添加到 ul 末尾,但最后创建的 li 未被识别为最后一个
我有以下代码。单击最后一个 li 上的按钮后,我可以创建新的 li。但是,一旦创建,如果我单击创建的最新按钮,则会创建新的 li。看来它没有将最后创建的 li 识别为最后一个 li。有人可以帮忙解决这个问题吗?
<html xmlns="http://www.w3.org/1999/xhtml" >
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#mylist :button").click(function() {
var text = $(this).val();
if (text == "Save") {
}
});
$("#mylist li:last-child").click(function() {
$(this).parent().append('<li>' + '<input type = "textbox">' + '<input type = "button" value= "Save">' + '</li>');
});
});
</script>
<div>
<ul id="mylist">
<li id="1">1<button id="Button3">Delete</button> </li>
<li id="2">2<button id="Button2">Delete</button></li>
<li id="3">3<button id="another_entry">Save</button></li>
</ul>
<ul id="mylist2">
<li> test1 <button id="Button6">Delete</button></li>
<li> test2<button id="Button5">Delete</button> </li>
<li id="6"><button id="Button1">Delete</button></li>
</ul>
</div>
I have the following code. On cliking the button on the last li, I can create the new li. However, once created, if I click on the latest button created, new li is created. It seems it doesn`t recognise the last created li as the last li. Can someone help on this please.
<html xmlns="http://www.w3.org/1999/xhtml" >
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#mylist :button").click(function() {
var text = $(this).val();
if (text == "Save") {
}
});
$("#mylist li:last-child").click(function() {
$(this).parent().append('<li>' + '<input type = "textbox">' + '<input type = "button" value= "Save">' + '</li>');
});
});
</script>
<div>
<ul id="mylist">
<li id="1">1<button id="Button3">Delete</button> </li>
<li id="2">2<button id="Button2">Delete</button></li>
<li id="3">3<button id="another_entry">Save</button></li>
</ul>
<ul id="mylist2">
<li> test1 <button id="Button6">Delete</button></li>
<li> test2<button id="Button5">Delete</button> </li>
<li id="6"><button id="Button1">Delete</button></li>
</ul>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
live
而不是bind
,因为绑定仅迭代元素一次,但是live
创建一个 侦听器,它动态附加事件,甚至附加到新创建的元素。您的代码应符合此示例:
使用
jQuery 1.4.0
进行测试You need to use
live
instead ofbind
as bind iterates elements only once, howeverlive
creates a listener, which attaches events dynamically, even to newly created elements.You code should conform to this sample:
tested with
jQuery 1.4.0
而不是:
尝试
Instead of:
Try