我想要获取被点击元素在其列表中以及其 .blue
类中的索引。
我已经弄清楚如何获取其列表中的索引,但无法弄清楚如何获取其 .blue
类中的索引。例如,当我点击第五个按钮时,希望显示“index 4 - class index 3”。
有什么想法吗?
$('.showindex').click(function() {
var index = $(this).closest("li").index();
console.log("index " + index + " - class index " + "?");
});
.blue {
color: blue;
}
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<ol id="ol1">
<li><input type="button" value="Show index" class="showindex blue">showindex blue</li>
<li><input type="button" value="Show index" class="showindex">showindex</li>
<li><input type="button" value="Show index" class="showindex blue">showindex blue</li>
<li><input type="button" value="Show index" class="showindex">showindex</li>
<li><input type="button" value="Show index" class="showindex blue">showindex blue</li>
</ol>
index()
方法传递参数:var blueIndex = $('.blue').index($(this));
。请注意,如果找不到任何内容,它将返回-1
。 - Reyno