我有这个HTML模板。
<template id="single_feed">
<div class="ibox" id="FIRST_DIV">
<div class="ibox-title">
<h5 id="naslov"></h5>
</div>
<div class="ibox-content">
<form method="get" _lpchecked="1">
<div class="form-group row"><label class="col-sm-2 col-form-label">Naziv</label>
</form>
</div>
</div>
</template>
现在我想克隆并改变第一个div的ID(现在设置为:"FIRST_DIV")。但是不知道怎么改。我只能改变第二个、第三个......divs。
我的jquery代码是用于克隆的。
$(".btn-RSS-single").click(function(e) {
var idClicked = e.target.id;
const $template = $( $('#single_feed')[0].innerHTML );
$template.find("div:first").attr("id", "NEW_ID_"+idClicked);
$('#kolona_1').append($template);
});
P.S:我删除了不必要的部分,使代码更易读。
jQuery有 .html()
函数来获取内部html和 .clone()
函数来克隆该元素。你可以同时使用这两个函数来实现你想要的东西,并使代码更易读。
请看这个例子(我改变了一些值,使例子更清楚)。
let clicked = 0;
$(".btn-RSS-single").click(function(e) {
var idClicked = e.target.id;
idClicked = clicked++;
const template = $("#single_feed").html();
$template = jQuery(template).clone().attr("id", "NEW_ID_" + idClicked);
$('#kolona_1').append($template);
});
#kolona_1 {
border: 1px solid gray;
}
#kolona_1 > div {
background-color: rgba(180, 180, 180, 0.2);
margin: 1em;
}
.btn-RSS-single {
background-color: lightblue;
padding: 0.2em 1em;
text-align: center;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="kolona_1"></div>
<div class="btn-RSS-single">ADD</div>
<template id="single_feed">
<div class="ibox" id="FIRST_DIV">
<div class="ibox-title">
<h5 id="naslov"></h5>
</div>
<div class="ibox-content">
<form method="get" _lpchecked="1">
<div class="form-group row"><label class="col-sm-2 col-form-label">Naziv</label></div>
</form>
</div>
</div>
</template>
希望这能帮到你
const template = (document.getElementsByTagName("template")[0]).content.cloneNode(true);
const firstDiv = template.querySelector("div");
firstDiv.id = "new id";
document.body.querySelector('#kolona_1').appendChild(firstDiv);
试试下面的东西
$(".btn-RSS-single").click(function(e) {
var idClicked = e.target.id;
const $template = $( $('#single_feed')[0].innerHTML );
$template.find("div:first").attr("class", "template-new"+idClicked);
$('#kolona_1').append($template);
$('#kolona_1').find('.template-new' + idClicked).attr('id', 'NEW_ID_' + idClicked);
});