我有两个 div .content。
我有一个“添加”按钮可以将段落添加到 .content div。
我希望每个 .content div 中最多有 3 个段落,当这两个 .content div 已经有 3 个段落时,我想创建一个新的 .content div 并在其中添加新段落。
但是它不能正常工作,当我向 .content div 添加新段落时,该段落会添加到所有 .content div 中,而我只想在一个 div 中添加一个段落。
您知道如何正确执行此操作吗?
$(document).on('click', '#input', function () {
$('#input').val('');
});
$(document).on('click', '#add', function () {
var input = $("#input").val();
alert(input);
var divContentSize = $(".container > *").length;
alert(divContentSize);
var relDiv = $(".container > div").filter(function () {
return $(this).children().length !== 3;
});
if (relDiv.length) {
relDiv.prepend("<p>" + input + "</p>");
}
else {
$(".container").append("<div class=content><p>" + input + "</p></div>");
}
});
$(".prev").click(function(){
if ($(".container .content:visible").next().length != 0)
$(".container .content:visible").fadeOut(function(){
$(this).next().fadeIn();
});
else {
$(".container .content:visible").fadeOut(function(){
$(".container .content:first").fadeIn();
});
}
return false;
});
$(".next").click(function(){
if ($(".container .content:visible").prev().length != 0) {
$(".container .content:visible").fadeOut(function(){
$(this).prev().fadeIn();
});}
else {
$(".container .content:visible").fadeOut(function(){
$(".container .content:last").fadeIn();
});
}
return false;
});
最佳答案
你可以看看这个 fiddle ,看看它是否能完成你想要的一切。我剥离了你的 fiddle 只是为了展示功能,并且还可以更轻松地浏览特定问题的代码。 Fiddle
我基本上使用 jquery 来遍历元素并决定点击事件中的内容:
$(document).ready(function(){
$("#add").click(function(){
//get last child of class content of container
var children = $(".container").children(".content");
//add new content if none exist
if(children.length <= 0 || $(children[children.length-1]).children("p").length == 3){
var div = $("<div class='content'/>");
$(".container").append(div);
}
//refresh children
children = $(".container").children(".content");
$(children[children.length - 1]).append("<p>Newly added</p>");
});
});
更新:刚刚更新了 fiddle ,以便更容易看到添加到 DOM 的 div 和 p 标签的分离
新 fiddle :Fiddle
更新:更新了 fiddle 以使用评论中所述的两个 div 内容运行。 Updated Fiddle
匹配下面的代码:
function addP2div(div){
$(div).append("<p>Newly added</p>");
}
$(document).ready(function(){
$("#add").click(function(){
//get children of class content of container
var children = $(".container").children(".content");
//set variable to see if added
var added = false;
//add new content if none exist
if(children.length > 1){
//check each child to see if it can accept a third p
for(i=0;i<children.length;i++){
var elem = children[i];
//skip if 3 p exist
if($(elem).children("p").length == 3){
continue;
}
//add p here
addP2div(elem);
added = true;
break;
}
}
//create new div and add to it
if(!added){
var div = $("<div class='content'/>");
$(".container").append(div);
addP2div($(".container").children('.content').last());
}
});
});
关于javascript - 每个 <p> 都会添加到所有 .content div 中,而不仅仅是一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33862053/