Javascript 使用jQuery插入列表项时出现问题
这里对jQuery非常陌生,但我尝试将无序列表插入DOM,然后插入列表项。正在正确插入,并已被赋予类.newList,但未追加元素。不应该。将它们插入ul 以下是HTML:Javascript 使用jQuery插入列表项时出现问题,javascript,jquery,html,list,append,Javascript,Jquery,Html,List,Append,这里对jQuery非常陌生,但我尝试将无序列表插入DOM,然后插入列表项。正在正确插入,并已被赋予类.newList,但未追加元素。不应该。将它们插入ul 以下是HTML: <!--List inserted with jQuery--> <button id="modifyExample2">Click me to insert a list!</button> 这是我的剧本: $("#modifyExample2").on("click", fu
<!--List inserted with jQuery-->
<button id="modifyExample2">Click me to insert a list!</button>
这是我的剧本:
$("#modifyExample2").on("click", function () {
if ($(this).prev("ul").hasClass("newList")) {
$(".newList").append("<li>New list item!</li>");
} else {
$("<ul>My new list!</ul>").insertBefore(this);
$(this).prev("ul").addClass("newList");
$("#modifyExample2").text("Click me again to insert list items!");
}
});
在JSFIDLE中:
有什么我误解了/遗漏了吗?你有打字错误;使用addClass和hasClass时,不需要使用。前缀: 请注意,您还可以稍微整理一下逻辑:
$("#modifyExample2").on("click", function () {
var $ul = $(this).prev('ul');
if ($ul.hasClass("newList")) {
$ul.append("<li>New list item!</li>");
} else {
$("<ul>My new list!</ul>").addClass("newList").insertBefore(this);
$(this).text("Click me again to insert list items!");
}
});
您有一个语法错误 这是一把小提琴: ul的类名必须是newList而不是.newList 请参见写下以下内容:
$(document).ready(function () {
$(document).on("click","#modifyExample2", function () {
if ($(this).prev().hasClass("newList")) {
$(this).prev().append("<li>New list item!</li>");
} else {
$("<ul>My new list!</ul>").insertBefore(this);
$(this).prev("ul").addClass("newList");
$(this).text("Click me again to insert list items!");
}
});
});
谢谢,错过了one@RoryMcCrossan先到那里。这是正确的answer@RoryMcCrossan非常感谢你发现了这一点,并为整理指针!语法错误确实是初学者的难题。addClass/hasClass'className'不应该有一个。-点。另外,您的小提琴正在使用onload和document.ready-useeither@mplungjan啊,谢谢,更新了小提琴。不。hasClass和addClass中没有点。另外,除非按钮是动态插入的,否则无需委托。只要您不使用“.newList”作为选择器,就可以了。没必要在这里投反对票,现在没事了。本来情况不好,我已经取消了否决票。Chrome不适用于hasClass和addClass中的点。现在,除了不必要的授权之外,它与
$(document).ready(function () {
$("#modifyExample2").on("click", function () {
if ($(this).prev("ul").hasClass("newList")) {
$(".newList").append("<li>New list item!</li>");
} else {
$("<ul>My new list!</ul>").insertBefore(this);
$(this).prev("ul").addClass("newList");
$("#modifyExample2").text("Click me again to insert list items!");
}
});
});
$("#modifyExample2").on("click", function () {
if ($(this).prev("ul").hasClass("newList")) {
$(".newList").append("<li>New list item!</li>");
} else {
$("<ul>My new list!</ul>").insertBefore(this);
$(this).prev("ul").addClass("newList");
$("#modifyExample2").text("Click me again to insert list items!");
}
});
$(document).ready(function () {
$(document).on("click","#modifyExample2", function () {
if ($(this).prev().hasClass("newList")) {
$(this).prev().append("<li>New list item!</li>");
} else {
$("<ul>My new list!</ul>").insertBefore(this);
$(this).prev("ul").addClass("newList");
$(this).text("Click me again to insert list items!");
}
});
});