始终使用jquery在动态折叠中显示前两行



我有一个页面有多个相同类的div,我使用下面的代码为所有div动态添加折叠类,但我的问题是,我总是想显示前两段。

这是我的代码:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="section-title"></div>
<div class="section-text"></div>
<div class="section-title"></div>
<div class="section-text"></div> 
<div class="section-title"></div>
<div class="section-text"></div> 

我的javascript:

var numItems = $('.section-title').length;
console.log(numItems );
var i;
for(i='0';i<numItems;i++) {
$(".section-title ").attr("data-toggle", "collapse");
$(".section-title ").attr("data-target", "#collapseOne"+i);
$(".section-text ").attr("data-toggle", "collapse");
$(".section-text").attr("id", "collapseOne"+i);
}
$(".section-title ").addClass("toggle");
$( ".section-text" ).css("display", "none");
$(".toggle").click(function()
{
// hides children divs if shown, shows if hidden
$(this).next().toggle();
});

尝试在代码中添加setAttribute。setAttribute()方法将指定的属性添加到元素中,并为其指定值。

$sectionText.setAttribute("data-toggle", "collapse");

用这个更新你的js:

$(function(){

const $sections = $('.section-title')
for (let i = 0; i< $sections.length; i++){
const $section = $sections.eq(i)
const $sectionText = $section.next()
$section.text(`Section ${i}`)
$sectionText.text(`Section Text ${i}`)
const targetId = `section_${i}`
$sectionText.attr('id',targetId)
$sectionText.addClass('collapse')
$sectionText.setAttribute("data-toggle", "collapse");
$section.attr('data-target',`#${targetId}`)
}
})

最新更新