使用 jQuery 最接近 class
Getting closest class using jQuery
我正在尝试抓取最近的元素中的文本,class 名称为 'the_text',但我遗漏了一些明显的东西。
$(document).on('click', '.click-class', function(e) {
var t = $(this);
alert(t.closest('.the_text').text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span class="the_text">Grab This Text</span>
<p>
</p>
<span><a class="click-class">Click</a></span>
</div>
单击 'Click' 时的结果是空的,但我希望它是 'Grab This Text'
JSFiddle:
https://jsfiddle.net/7c9w3f62/
closest
只搜索自身并向上遍历其祖先
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
您将需要获得最接近的 div
然后使用 find
$(document).on('click', '.click-class', function(e) {
var t = $(this);
alert(t.closest('div').find(".the_text").text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span class="the_text">Grab This Text</span>
<p>
</p>
<span><a class="click-class">Click</a></span>
</div>
我正在尝试抓取最近的元素中的文本,class 名称为 'the_text',但我遗漏了一些明显的东西。
$(document).on('click', '.click-class', function(e) {
var t = $(this);
alert(t.closest('.the_text').text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span class="the_text">Grab This Text</span>
<p>
</p>
<span><a class="click-class">Click</a></span>
</div>
单击 'Click' 时的结果是空的,但我希望它是 'Grab This Text'
JSFiddle: https://jsfiddle.net/7c9w3f62/
closest
只搜索自身并向上遍历其祖先
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
您将需要获得最接近的 div
然后使用 find
$(document).on('click', '.click-class', function(e) {
var t = $(this);
alert(t.closest('div').find(".the_text").text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span class="the_text">Grab This Text</span>
<p>
</p>
<span><a class="click-class">Click</a></span>
</div>