简体   繁体   English

使用jQuery获取距离最近的文本

[英]Get text from closest span using jQuery

I'm looking to retrieve the text inside a HTML table that is rendered via a webgrid. 我正在寻找通过Webgrid呈现的HTML表中的文本。 The text that I want is located inside a div with the class productID . 我想要的文本位于带有class productIDdiv My starting reference point is in the same row but the last td with the class span2 . 我的起始参考点在同一行中,但最后一个td带有span2类。 I'm trying to use jQuery's closest() method however I'm not getting any value returned. 我正在尝试使用jQuery的最近的()方法,但是没有返回任何值。

Please see below for a section of the rendered HTML and my jQuery function: 请参阅以下有关呈现的HTML和我的jQuery函数的部分:

HTML: HTML:

<tr>
    <td class="span1"><div class="productID">1</div></td>
    <td class="span2">Listing</td>
    <td class="span2">Full Districtution</td>
    <td class="span2">$1,350.00</td>
    <td class="span2">2016-01-01</td>
    <td class="span2"><div title="This is my brand new title!" data-original-title="" class="priceToolTip">2016-04-30</div></td>
    <td><a href="/product/AddOrEditProduct?productID=1">Select</a></td>
</tr>

jQuery: jQuery的:

$(".priceToolTip").mouseover(function () {
    var row = $(this).closest("span1").find(".productID").parent().find(".productID").text();
    console.log("Closest row is: " + row);
});

The .closest() method looks for a match in the ancestors. .closest()方法在祖先中查找匹配项。 So you can use it to grab the tr then look for .productID like so: 因此,您可以使用它来获取tr然后像下面这样查找.productID

var productID = $(this).closest('tr').find('.productID').text();

Or: 要么:

var productID = $(this).parent().find('.productID').text();

Or: 要么:

var productID = $(this).siblings('.span1').find('.productID').text();

.span1 is not the closest element of .priceToolTip . .span1不是最亲密的元素.priceToolTip Use closest("tr").find(".span1 .productID") like following. 使用如下所示的closest("tr").find(".span1 .productID")

$(".priceToolTip").mouseover(function () {
    var row = $(this).closest("tr").find(".span1 .productID").text();
    console.log("Closest row is: " + row);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM