【发布时间】:2022-11-24 23:37:54
【问题描述】:
当用户使用 jquery 检查复选框时,我这样做会获取 html 元素的值。我没有使用 id 因为这是重复行功能
我正在尝试这个
$(document).on('click', '.row_checkbox ', function() {
if (this.checked) {
console.log("checked");
var unit_price = $(this).parent().prev().children().val();
console.log(unit_price);
} else {
}
});
<table>
<tr>
<td>
<input type="text" class="form-control row_price" name="order_innerprice[]">
</td>
<td>
<label class="checkbox checkbox-custom-alt">
<input type="checkbox" class="form-control row_checkbox" name="order_checkbox[]"><i></i>
</label>
</td>
</tr>
</table>
【问题讨论】:
-
我重新格式化了您的代码,以便您清楚地看到
input的parent()是label。所以没有prev或children。将$(this).parent()更改为$(this).closest("td") -
我已经解决了我的问题
-
使用
.parent().parent()也是一个坏主意,出于同样的原因 - 如果您将来更改布局,例如您选择不使用标签包装器并将标签作为输入的兄弟,您的代码将再次失败。