I have a pagination button structure like below, they are constructed by DataTable中获取特定的文本。如何获得<a>
标签之间的文本?或者我可以在这些标签中添加id
<ul class="pagination">
<li class="paginate_button previous disabled" aria-controls="test" tabindex="0" id="test_previous">
<a href="#">Prev</a>
</li>
<li class="paginate_button" aria-controls="test" tabindex="0">
<a href="#">1</a>
</li>
<li class="paginate_button" aria-controls="test" tabindex="0">
<a href="#">2</a>
</li>
<li class="paginate_button" aria-controls="test" tabindex="0">
<a href="#">3</a>
</li>
<li class="paginate_button next disabled" aria-controls="test" tabindex="0" id="test_next">
<a href="#">Next</a>
</li>
</ul>
我试图这样做:
var newText = $('.paginate_button a').text();
console.log(text);
它给了我: 上一页123下一页
答案 0 :(得分:2)
$('.paginate_button a')
返回与选择条件匹配的元素的每个的 NodeList 集合。在此示例中,每个<a>
元素都有一个父.paginate_button
元素,因此每个元素都是匹配的。
如果要选择特定的,只需引用NodeList的索引(并使用.innerText
代替.text())
:
var newText = $('.paginate_button a')[0].innerText;
console.log(newText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="pagination">
<li class="paginate_button previous disabled" aria-controls="test" tabindex="0" id="test_previous">
<a href="#">Prev</a>
</li>
<li class="paginate_button" aria-controls="test" tabindex="0">
<a href="#">1</a>
</li>
<li class="paginate_button" aria-controls="test" tabindex="0">
<a href="#">2</a>
</li>
<li class="paginate_button" aria-controls="test" tabindex="0">
<a href="#">3</a>
</li>
<li class="paginate_button next disabled" aria-controls="test" tabindex="0" id="test_next">
<a href="#">Next</a>
</li>
</ul>
或者,您可以使用诸如 .first()
之类的选择器来定位单个结果:
var newText = $('.paginate_button a').first().text();
console.log(newText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="pagination">
<li class="paginate_button previous disabled" aria-controls="test" tabindex="0" id="test_previous">
<a href="#">Prev</a>
</li>
<li class="paginate_button" aria-controls="test" tabindex="0">
<a href="#">1</a>
</li>
<li class="paginate_button" aria-controls="test" tabindex="0">
<a href="#">2</a>
</li>
<li class="paginate_button" aria-controls="test" tabindex="0">
<a href="#">3</a>
</li>
<li class="paginate_button next disabled" aria-controls="test" tabindex="0" id="test_next">
<a href="#">Next</a>
</li>
</ul>
答案 1 :(得分:1)
我认为您想获取clicked标签的文本,对吧?
然后尝试此代码
$('body').on('click', '.paginate_button a', function(e){
console.log($(this).text());
});