使用JQuery从表行中的控件中选择文本

时间:2009-10-20 16:07:50

标签: jquery

我有一个包含5个单元格的表格行。

我想点击最后一个单元格中的图片,并从第一个单元格中的单选按钮获取文本值。

有人可以告诉我需要的jQuery命令吗?

我目前正在这样做:

// when the image is clicked

alert($(this)[0].parentElement.parentElement.children[0].childNodes[1].innerText);

但有些事情告诉我,这有点过于冗长而不正确。

任何想法?

由于

戴夫

3 个答案:

答案 0 :(得分:1)

Markup很高兴在这里知道,单选按钮:有不止一个?如果是这样,只需要选择一个?您可以使用以下选择器: 选中一个:

$(this).parent().sibling('td').children('input:radio:checked').val();

第一栏选中了一个:

$(this).parent().sibling('td:first').children('input:radio:checked').val();

答案 1 :(得分:0)

可能是这样的:

$(this).closest('tr').find('td:first input[type=radio]').val();

没有你的标记会有点困难,但这应该是一个好的开始。

答案 2 :(得分:0)

标记示例。 (使用按钮而不是img)

<table border="1">
    <tr>
        <td><input type="radio" name="example" value="foo" /> Foo Label</td>
        <td>stuff</td>
        <td><button onclick="checkIt(this)">Check it</button></td>
    </tr>
</table>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>

<script type="text/javascript">

    function checkIt(button){  
        // Alert the value of the radio
        alert($(button).parents('tr').find('td:first :radio').val());

        // Alert the label of the radio
        alert($(button).parents('tr').find('td:first').contents().filter(function() {
            return this.nodeType == Node.TEXT_NODE;
        })[0].data)
    };  
</script>

编辑:添加了标签提醒()