所以我试图通过jquery动态地向内容添加内容。 Span位于无序列表中。我想将每个li的索引号添加到span中,所以它看起来像这样:
提供者1
提供者2
提供者3
我将如何解决此问题
但目前正在这样做
提供者1
提供者1
提供者1
jQuery(document).ready(function () {
var timesClickedIndex = $('.timesClicked').closest("li").index() + 1;
$('.timesClicked').html('Providor '+timesClickedIndex);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
</ul>
答案 0 :(得分:2)
您可以使用以下内容(使用jquery each()上的索引)。
jQuery(document).ready(function () {
$('.timesClicked').each(function(i,e) { $(e).html('Providor '+ (i+1)); });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
</ul>
你的代码不起作用的原因是因为你使用它时index()总是会产生1而你只是将这个单一值应用于所有元素。您可以使用index(),如以下示例所示,但代码过于复杂,而不是上面的示例:
jQuery(document).ready(function () {
$('.timesClicked').each(function(i,e) {
$(e).html('Providor '+ ($('.timesClicked').index(e) + 1));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
</ul>
答案 1 :(得分:2)
您可以使用每个jquery函数执行此操作。 https://api.jquery.com/each/
jQuery(document).ready(function () {
var timesClickedIndex = $('.timesClicked').each(function( index )
{
$(this).html('Providor ' + (index + 1));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
</ul>
答案 2 :(得分:2)
您可以使用.each()
遍历跨度并使用index参数对它们进行编号:
jQuery(document).ready(function() {
$('.timesClicked').each(function(i) {
$(this).html('Providor ' + (i+1));
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
</ul>
答案 3 :(得分:2)
jQuery(document).ready(function () {
$('.timesClicked').each(function(key){
$(this).html('Providor '+ (key+1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
<li>
<div>
<span class="timesClicked"></span>
</div>
</li>
</ul>