无法从中<tempate>更改第一个元素的 divs ID



我有这个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);
});     

附言: 我删除了不必要的部分以使代码更具可读性。

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);

}(;

最新更新