我的应用程序有这样的HTML结构:
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2018</h2>
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2017</h2>我想通过jQuery将我的HTML模板添加到相关的类中。例如:
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2018</h2>
<div>2018 content</div>
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2017</h2>
<div>2017 content</div>首先,获取我的父类数据:
var array = $('.timeline__section h2').map(function () {
return $.trim($(this).text());
}).get();然后我使用了jQuery.inArray函数:
if (jQuery.inArray(year, array) === 1) {
console.log("yes");
}起作用了。
但是现在,我需要将我的HMTL模板追加到相关的类中。试过这个把戏,但效果不佳。(将HTML添加到各处,而不是相关区域。)
if (jQuery.inArray(year, array) === 1) {
$($(".timeline__section h2").text(this)).append("<div class=\"col-10 col-md-6 col-lg-4 d-flex align-items-stretch\">"");
}问题是什么,实现这一目标的正确途径是什么?
发布于 2019-08-25 18:18:09
.append()方法将内容插入元素的末尾,但您需要在元素后面插入内容。所以使用.after()
$('.timeline__section h2').after(function () {
return "<div>year content</div>";
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="timeline__section">
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2018</h2>
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2017</h2>
</div>
此外,如果您每年都有自定义数据,请使用底部代码。
var data = {
2018: '2018 content',
2017: '2017 content'
}
$('.timeline__section h2').after(function () {
var year = $(this).text().trim();
if (data[year] != undefined)
return "<div>"+data[year]+"</div>";
});
var data = {
2018: '2018 content',
2017: '2017 content'
}
$('.timeline__section h2').after(function () {
var year = $(this).text().trim();
if (data[year] != undefined)
return "<div>"+data[year]+"</div>";
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="timeline__section">
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2018</h2>
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2017</h2>
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2016</h2>
</div>
https://stackoverflow.com/questions/57648510
复制相似问题