jquery点击兄弟选择

时间:2012-11-02 10:54:34

标签: jquery html onclick

我从数据库生成一个表,看起来像这样

<table id="items">
<thead>
    <tr>
        <th>Details</th>
        <th>Goldmine ID</th>
        <th>&nbsp;</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td class="evenrow">This is a test Description generated through UNIT Tests for the category description</td>
        <td class="evenrow"><input type="text" value="" id="106" class="gminput"></td>
        <td class="butCell evenrow"><button class="saveButton updateitem">Update</button></td>
    </tr>
    <tr>
        <td class="oddrow">This is a test Description generated through UNIT Tests for the category description</td>
        <td class="oddrow"><input type="text" value="" id="107" class="gminput"></td>
        <td class="butCell oddrow"><button class="saveButton updateitem">Update</button></td>
    </tr>
    <tr>
        <td class="evenrow">This is a test Description generated through UNIT Tests for the category description</td>
        <td class="evenrow"><input type="text" value="" id="108" class="gminput"></td>
        <td class="butCell oddrow"><button class="saveButton updateitem">Update</button></td>
    </tr>
</tbody>
</table>

我正在尝试获取相关行按钮返回的输入框值和ID

到目前为止,我已经尝试了这个但是失败了

$('body').on('click', '.updateitem', function(event) {
    event.preventDefault();
    $(this).parent().siblings().each(function(index) {
        alert(($(this).val()));
    });
    var par = sib.parent('td');
    par.addClass('redBorder');
});

3 个答案:

答案 0 :(得分:4)

您想要的元素是

$(this).closest('tr').find('.gminput')

您可以使用

获取值和ID
var input = $(this).closest('tr').find('.gminput');
var value = input.val();
var id = input.attr('id');

答案 1 :(得分:0)

jQuery中没有方法forEach() ..尝试.each()

$(this).parent().parent().each(function(index) {
   if(!$(this).hasClass('butCell')) {
       if($(this).find('input').length > 0) { // we have to verify if tds has text inputs or not
           alert($(this).find('input').val());
       } else {
           // if there is no text input we get the text inside td
           alert($(this).text());
       }
   }  
});

答案 2 :(得分:0)

$('.updateitem').on('click', function(){
    $elem = $(this).parents('tr').find('.gminput');
    var id = $elem.prop('id');
    var val = $elem.val()
})

为什么body上有点击事件,button可能就足够了?