选择第一个兄弟姐妹

时间:2010-01-27 11:04:16

标签: jquery html dom siblings jquery-1.3.2

我正试图在我无法改变html标记的环境中选择第一个兄弟的内部值 - 使用jQuery。

我有以下内容:

<tr>
    <td>3</td>
    <td>bob</td>
    <td>smith</td>
    <td>bob@example.com</td>
    <td>
        <img src="bobsmith.png" onclick="doSomething()" />
    </td>
</tr>

我正在尝试使用以下内容获取第一个<td>的值:

function doSomething() {
    var temp = $(this).parent().parent().children().filter(':first');
    alert("you clicked person #" + temp.html());
}

我得到的只是null

我也尝试过与.siblings()功能的各种组合,但无济于事。

有什么想法吗?

谢谢,

注意:我忘了提到摘录的表是动态加载的&amp;从ajax电话刷新。这可能与包含绑定的建议相关。

解决方案: 我接受了以下解决方案,灵感来自公认的答案:

<tr>
    <td>3</td>
    <td>bob</td>
    <td>smith</td>
    <td>bob@example.com</td>
    <td>
        <img src="bobsmith.png" onclick="doSomething(this)" />
    </td>
</tr>

和jQuery javascript:

function startStopNode(el) {
    var temp = $(el).parent().siblings(':first').html();
    alert("you clicked: " + temp);
}

6 个答案:

答案 0 :(得分:17)

$( 'td:first-child', $( this ).parents ( 'tr' ) ).html ();

这将选择图像的父TR中的第一个TD元素(:first-child过滤器)。 parents()返回元素的所有父元素,并且我们过滤父元素,以便只返回TR元素。

也可以尝试这样写你的图像:

<img src="bobsmith.png" onclick="doSomething(this)" />

和你的功能如下:

function doSomething ( imgEl ) {
}

并使用imgEl代替this

答案 1 :(得分:2)

$('tr td:last-child img').click(function(){

    alert($('td:first-child',$(this).closest('tr')).text());

});

答案 2 :(得分:2)

我会使用jQuery设置一个事件,但这完全取决于你。

$("table td:last img").click(function() {
    var firstTd = $(this).parents("tr").find("td:first").html();
    alert("you clicked person #" + firstTd);
}); 

无论如何,您仍然可以将此示例与您自己的代码一起使用:

function doSomething()
{
    var firstTd = $(this).parents("tr").find("td:first-child").html();
    alert("you clicked person #" + firstTd);
}

你是对的。 '这个'没有被传递,你需要编辑html才能使它工作。或者只是使用jQuery代替如上所示。

答案 3 :(得分:0)

也许这会对某人有所帮助。这只是整篇文章here的一部分。

差异

如果要使用它来访问处理事件的HTML元素,则必须确保this关键字实际写入onclick属性。只有在这种情况下它才会引用事件处理程序注册的HTML元素。所以,如果你这样做

element.onclick = doSomething;
alert(element.onclick)

你得到了

function doSomething()
{
    this.style.color = '#cc0000';
}

如您所见,onclick方法中存在this关键字。因此它引用了HTML元素。

但如果你这样做

<element onclick="doSomething()">
alert(element.onclick)

你得到了

function onclick()
{
    doSomething()
}

这仅仅是函数doSomething()的引用。 onclick方法中不存在this关键字,因此它不引用HTML元素。

答案 4 :(得分:0)

我们有一个表行,其中一列是操作,其他列包含数据。其中一列包含产品代码(UPC)。因此,只要有人点击操作按钮,我们就会使用它来显示产品代码:

var product_code = jQuery(obj).parents('tr').children('.upc').text();
alert('product code'+product_code);

这是有效的,因为我们的表格单元格有类,例如每行1919191911919。

但是,您可以使用jQuery中的其他选择器。例如.children('#myid'),如果您在单元格19191919199191上设置了id属性,以及任何数量的其他选择器,如.children(td:first),以获取同一行上的第一个单元格。

答案 5 :(得分:0)

真的,在这种用例中不需要jquery。因此,对于那些浏览一般性答案而不是专门针对jquery的人,或者那些渴望获得性能更高的解决方案的人。该解决方案比其jquery同类解决方案快大约10倍。 See reference

function doSomething(el) {
    var temp = el.closest('tr').firstElementChild.innerHTML;
    alert("you clicked: " + temp);
}
相关问题