使用动态id jquery获取类的值

时间:2016-11-21 18:08:32

标签: javascript jquery html

我有下表,我想从前一个输入的$('.note')获取输入id值:

<tr>
    <td><input type="text" id='student_1' class='student'></td> 
    <td><input type="text" class='note'></td>
</tr>
<tr>
    <td><input type="text" id='student_2' class='student'></td> 
    <td><input type="text" class='note'></td>
</tr>

所以它可以是这样的:

$(".student").change(function () {
    alert(this.id.parent('td input.note').val())
})

3 个答案:

答案 0 :(得分:4)

您可以使用this.value$(this).val()

$('.classname').on('click',function(){
   console.log(this.value, $(this).val(), this.id);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='classname' id="id_1" value='value_1'/>
<input type='text' class='classname' id="id_2" value='value_2'/>
<input type='text' class='classname' id="id_3" value='value_3'/>
<input type='text' class='classname' id="id_4" value='value_4'/>

修改:

使用tr转到父.closest('tr'),然后使用note搜索相关输入.find('.note')并获取值:

$(".student").on('input', function () {
  console.log( $(this).closest('tr').find('.note').val() );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input type="text" id='student_1' class='student'></td> 
    <td><input type="text" class='note' value="1111"></td>
  </tr>
  <tr>
    <td><input type="text" id='student_2' class='student'></td> 
    <td><input type="text" class='note' value="2222"></td>
  </tr>
</table>

答案 1 :(得分:1)

您可以使用closestfind的组合。

$(".student").on('change', function () {
   // the student input to which the change event is bound
    var $this = $(this);
    // Get the wrapper in which the inputs are present
    var $closestTr = $this.closest('tr');
    // the input vale that is needed
    alert($closestTr.find('.note').val());

});

答案 2 :(得分:0)

是的,您可以执行此操作$('#' + this.id).val()

您不需要在选择器中包含该类,因为ID是唯一的。