使用非唯一标识符查找与jQuery的同级

时间:2019-05-08 07:30:21

标签: jquery html

我有一张inputforms表,一行大概是这样

    <tr>
     <td><input name ="surname"></td>
     <td><input name = "forename"></td>
     <td><button onclick="test(this)">SAVEME</button></td>
    </tr>

test(param)函数应使用jquery来迭代按钮的同级并通过其name属性选择它们。这可能吗?或者,如果没有,我还有什么其他方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以找到最接近的tr和每个这样的输入

function test(val){
  $(val).closest('tr').find('input').each(function(index, item){ 
    if($(item).attr('name') == 'surname'){
       console.log('Surname');
       // handle your logic with name surname here
    }
  })
}

function test(val){
  
  $(val).closest('tr').find('input').each(function(index, item){ 

    if($(item).attr('name') == 'surname'){
	   console.log('Surname');
	}
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<table>
<tr>
     <td><input name ="surname"></td>
     <td><input name = "forename"></td>
     <td><button onclick="test(this)">SAVEME</button></td>
    </tr>
	</table>
</body>

相关问题