Добавить дополнительный html к клонированному объекту в jquery
Я хочу добавить дополнительный html в клонированный объект.
var item = $("#clone")
.clone(true, true)
.attr({"id": "citem", "class": "row cartItem_" + item_id})
.css('display', 'block')
.appendTo("#all-items");
Я знаю об методе обертки, но это что-то еще. Я хочу добавить html после этого клонированного объекта. Или каким-то образом я могу манипулировать HTML-элементом клонированного объекта.
Ответы
Ответ 1
Предполагая, что вы пытаетесь добавить html после клонирования:
$("#toclone")
.clone()
.attr({"id":"cloned"})
.appendTo("#all-items")
.after("<div>some more content <em>after</em> the clone</div>");
.appendTo()
возвращает добавленный элемент, поэтому вы можете его обрабатывать по мере необходимости, например, используя .after()
Ответ 2
Этот подход объясняет, как работает .clone()
, и охватывает все состояния, которые вы когда-либо упоминали в вопросе, например..
- Создание клона DOM
- Добавление дополнительного необработанного HTML в клон
- Управление клоном
- Манипуляция контентом в клоне
- Клон в другом клоне
- Добавление другого клона в клон
- Добавление HTML после этого клонированного объекта
$(function() {
//! Cloning the HTML
var $clonedContent = $('.content').clone();
// Manipulate the cloned element
// -- Update the existing content
$clonedContent.find('h5').text("My content just got manipulated");
// -- Adding raw HTML content
$clonedContent.append("<small> It a raw HTML </small>");
// -- Adding property to an existing content
$clonedContent.find('small').addClass('make-me-day');
//! Getting another cloned content
var $anotherClonedContent = $('.content').clone();
// -- Another manipulation of another cloned content
$anotherClonedContent.find('h5').text("This is another cloned content");
// -- Manipulate the another cloned content content
$anotherClonedContent.find('h5').addClass('make-me-day');
// -- Add another cloned content to the already manipulated & cloned content.
$clonedContent.append($anotherClonedContent);
//! Finally, add the clonedContent to the DOM, aaaand.. add more HTML afterwards.
$('#main').append($clonedContent, "<em> I added this HTML after the cloned object </em>");
});
.make-me-day {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<div class="content">
<h5> Just a simple content </h5>
</div>
</div>
Ответ 3
Я думаю, что это проще, чем вы думаете:
$(function(){
var item_id=0;
// function to clone your element
var newItem=function(){
item_id++;
return $('#clone')
.clone(true, true)
.attr({'id':'citem_'+item_id, 'class':'row cartItem_'+item_id})
.css('display','block')
.appendTo('#all-items');
};
// Clone element and edit what you want
newItem().html('hobby').css('color','blue');
// Clone element and append what you want
newItem().append(' - <i>spaghetti</i>');
// You can also find element by id
$('#citem_2').css('color','red');
//You can add buttons to do it
$('button:eq(0)').on('click',function(){
newItem().html('Your <b>html</b> here.');
});
$('button:eq(1)').on('click',function(){
newItem().append(' - Your <b>html</b> here.');
});
});
<button>New clone</button>
<button>New clone + append</button>
<div id="all-items">
<div id="clone">pizza</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Ответ 4
Я внимательно рассмотрел все ответы и комментарии к этому вопросу о щедрости...
Я вижу, что претендент является довольно требовательным, и это нормально с 100 rep. очки ценны.
Я думаю, что на самом деле вопрос состоит из двух.
- Как клонировать
- Как "манипулировать HTML-клонированным объектом" - Wasif Iqbal от 22 сентября.
Я думаю, что этот вопрос предназначен для того, чтобы получить объяснения о том, как манипулировать клоном, а не только о создании и добавлении где-то, но и потом.
Я действительно считаю, что мой очень классный пример ниже может быть "действительным ответом" - Vixed 29 сентября.
В любом случае, другие ответы тоже были хороши... Итак, сделано дополнительное усилие.
;)
Первое объяснение всего:
Клонирование элемента выполняется с помощью jQuery .clone()
. Так что хорошо читайте.
Тогда:
jQuery chaining приятно добавить некоторые другие вещи "внутри" или "до/после" клона в сжатом виде, как показано в других ответы.
Но манипулировать им впоследствии, как и в другом обработчике событий клика...
Это трюк, который нужно знать, что не объясняется в предыдущей ссылке:
- Вы должны установить для него уникальный атрибут
id
вместо того же самого id
в качестве оригинала.
Поскольку вы знаете, что id
будет уникальным!
"Одно кольцо, чтобы править ими.
Одно кольцо, чтобы найти их, одно кольцо, чтобы привести их всех и в темноте связывать их".
- Известный деамон сказал это, выкопав проклятие...
Затем... Что еще можно объяснить, если это не ясно?
Предупреждающий читатель должен был все понять уже.
Я сделал забавную "clone-and-kill-it-game" , чтобы демонировать клонирование и дальнейшие манипуляции.
Для "вдохновения" я должен признать, что вчера ночью увидел японский зомби-фильм...
лол!
Получайте удовольствие от этого фрагмента кода:
(также на CodePen)
// Constants
var number = 1;
var revealed = false;
// The cloning function
$("#cloneIt").click(function(){
var cloning = $("#Human")
.clone()
.attr({"id": "Clone_number_"+number, "class":"clone"})
.appendTo("#CloneBucket");
$(this).val("Clone him again! It fun!");
number++;
if(number==4){
$(".reveal").show();
}
if(number==9){
$(this).val("Enought! This is now illegal.").prop("disabled",true);
}
// Add them to select
var options="<option disabled selected class='deceased'>KILL THEM!</option>";
for (i=1;i<number;i++){
if( $("#CloneBucket").children().eq(i-1).hasClass("dead") ){
options += "<option value='"+i+"' class='deceased'>Clone #"+i+"</option>";
}else{
options += "<option value='"+i+"'>Clone #"+i+"</option>";
}
}
$("#cloneSelect").html(options);
if(revealed){
reveal(); // Sub function to add clones to a select element.
}
});
// Reveal clone numbers
$(".reveal").click(function(){
reveal();
setTimeout(function(){
$(".reveal").val("Kill a clone! (While it not illegal!)").removeClass("reveal").addClass("shoot");
},50);
});
// Kill button
$("#page").on("click",".shoot",function(){
$(this).prop("disabled",true).val("Select one");
$("#cloneSelect").show();
});
// Select kill target
$("#cloneSelect").change(function(){
var thisCloneIs = parseInt($(this).val());
var niceShot = "#Clone_number_"+thisCloneIs;
$(niceShot).css({"opacity":0.3,"color":"red"});
$(niceShot+" .definition").html("I was the number"+thisCloneIs).parent().addClass("dead");
// Redish the option
$(this).find("option").eq(thisCloneIs).prop("disabled",true).addClass("deceased");
$(this).find("option").eq(0).prop("selected",true);
// Bravo!
var allDead = [];
setTimeout(function(){
$("#cloneSelect").find("option").each(function(index){
if( $("#cloneSelect").find("option").eq(index).hasClass("deceased") ){
allDead.push(true);
}else{
allDead.push(false);
}
});
if( allDead.indexOf(false)==-1 ){
// Reset this super gaming experience for a new.
$("#CloneBucket").html("");
$(".shoot").addClass("reveal").removeClass("shoot").val("Reveal clone numbers!").prop("disabled",false).hide();
$("#cloneIt").val("Clone again?").prop("disabled",false);
$("#cloneSelect").html("").hide();
revealed = false;
number = 1;
}
},50);
});
function reveal(){
$(".clone .definition").each(function(index){
var cloneIndex = index+1; // zero-based
$(this).html("I'm the number "+cloneIndex);
revealed = true;
});
}
img{
width:60px;
}
div{
text-align:center;
}
.reveal{
display:none;
}
#CloneBucket div{
display:inline-block;
padding:10px;
}
#CloneBucket{
margin:0 auto;
text-align:center;
}
select{
display:none;
margin:0 auto;
}
.deceased{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div id="page">
<input type="button" id="cloneIt" value="Want to clone him?"><br>
<br>
<div id="Human">
<img src="http://image.flaticon.com/icons/svg/10/10522.svg"><br>
<span class="definition">I'm a real human!</span>
</div>
<br>
<input type="button" class="reveal" value="Reveal clone numbers!">
<select id="cloneSelect"></select>
<div id="CloneBucket"></div>
<br>
</div>
Ответ 5
Все еще ожидая пояснений в комментариях, но я думаю, что это решение - это то, что вы ищете:
$('button').click(function() {
$('#clone').clone()
.append('<span style="color:red;">some other elements</span>')
.removeAttr('id')
.appendTo('#all-items');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Click to clone</button>
<div id="all-items">
<div id="clone">pizza</div>
</div>
Ответ 6
Можно добавить коллекцию в любое время, используя функцию jQuery add()
.
Это эффективно добавляет коллекцию, помещая все, что передается в add()
после самого клона, в отличие от append
, который помещает содержимое внутри клона, отвечая на вопрос
"Я хочу добавить html после этого клонированного объекта"
var more1 = $('<span />', {html : '<em> and will</em>'}); // element(s) to add
var more2 = '<span> happen again....</span>'; // or strings of HTML for that matter
var item = $("#clone").clone(true, true)
.attr({"id": "citem"})
.show()
.add(more1) // add whatever after the clone
.add(more2) // before appending everything
.appendTo("#all-items");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="clone">
<span>All of this has happened before</span>
</span>
<br /><br /><br />
<div id="all-items"><!-- clone goes here --></div>