通过 jQuery 将文本添加到输入字段
Add text to input field via jQuery
我需要在单击按钮后向输入文本字段添加文本。按钮 class 总是相同的 (".button") 所以我想我需要使用 "$(this)" 但我不知道该怎么做。
我的代码是:
HTML:
<div class="add">
<input type="text" name="input[1]" value="" class="input[1]">
<input type="button" class="button" value="add">
</div>
<div class="add">
<input type="text" name="input[2]" value="" class="input[2]">
<input type="button" class="button" value="add" value="add">
</div>
<div class="add">
<input type="text" name="input[3]" value="" class="input[3]">
<input type="button" class="button" value="add">
</div>
jQuery:
$('.button').click(function(e) {
$(this).parent('input[type=text]').val('hhh');
});
此致:)
尝试用 .prev()
代替 .parent()
; input type="text"
似乎是 .button
元素的 .previousElementSibling
$(this).prev("input[type=text]").val("hhh");
使用最近的
$(this).closest('input[type="text"]').val('hhh')
我需要在单击按钮后向输入文本字段添加文本。按钮 class 总是相同的 (".button") 所以我想我需要使用 "$(this)" 但我不知道该怎么做。
我的代码是:
HTML:
<div class="add">
<input type="text" name="input[1]" value="" class="input[1]">
<input type="button" class="button" value="add">
</div>
<div class="add">
<input type="text" name="input[2]" value="" class="input[2]">
<input type="button" class="button" value="add" value="add">
</div>
<div class="add">
<input type="text" name="input[3]" value="" class="input[3]">
<input type="button" class="button" value="add">
</div>
jQuery:
$('.button').click(function(e) {
$(this).parent('input[type=text]').val('hhh');
});
此致:)
尝试用 .prev()
代替 .parent()
; input type="text"
似乎是 .button
元素的 .previousElementSibling
$(this).prev("input[type=text]").val("hhh");
使用最近的
$(this).closest('input[type="text"]').val('hhh')