不确定这是否可能,我有一个包含多个输入的页面,每个输入都有一个按钮。是否可以在不对输入 ID 进行硬编码的情况下在单击按钮时获取输入值?
例子
js
$('button').click(function () {
var inputcontent = $('input').prop('id');
console.log(inputcontent);
});
html
<input type="text" id="1">
<button type="button">Go!</button>
<input type="text" id="2">
<button type="button">Go!</button>
<input type="text" id="3">
<button type="button">Go!</button>
<input type="text" id="99">
<button type="button">Go!</button>
最佳答案
$('input').prop('id')
返回选择器中第一个匹配元素的 ID。要在每个按钮之前定位输入,您需要使用 .prev()
和 $(this)
。
试试这个:
$(this).prev().attr('id');
关于javascript - 单击按钮获取变量输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23519299/