不确定这是否可能,我有一个带有多个输入的页面,每个输入都有一个按钮。无论如何在按钮点击时获取输入值,而不对输入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>
答案 0 :(得分:3)
$('input').prop('id')
返回选择器中第一个匹配元素的id。要在每个按钮之前定位输入,您需要使用.prev()
和$(this)
。
试试这个:
$(this).prev().attr('id');
<强> Working Demo 强>
答案 1 :(得分:1)
你已经做得对了,只需改变代码中的一点点。您必须找到输入字段的值,该字段位于您将单击的按钮之前。所以你的代码应该是:
$('button').click(function () {
var inputcontent = $(this).prev().prop('id');
console.log(inputcontent);
});
答案 2 :(得分:0)
您并未定位您想要ID的项目,即按钮之前的输入。使用prev(0来做到这一点。另外,id实际上是一个属性,而不是属性,所以你应该这样做 -
$('button').click(function () {
var inputID = $(this).prev().attr('id'); // gets the id of the input that precedes the button
console.log(inputID);
});
答案 3 :(得分:0)
这将解决问题
$('button').click(function () {
var value = $(this).prev().val();
console.log(value);
});