我有两个带打开和关闭按钮的输入,当我打开第二个输入并输入值然后将其删除时,值保留在输入中它不会消失,我尝试了一些东西,但它没有'工作,这是我的代码:
$(function() {
$('#openInput').click(function() {
$('.secondInput').toggle()
});
});
$("#closeInput").click(function () {
$('.secondInput').toggle();
$('.secondInput').val('');
});

.secondInput{
display:none;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" class="form-control" />
<button type="button" id="openInput">Open</button><br>
<br>
<div class="secondInput">
<input type="text" class="form-control"/>
<button type="button" id="closeInput">Close</button>
</div>
&#13;
答案 0 :(得分:2)
您有两个问题:
$(function() {
$('#openInput').click(function() {
$('.secondInput').toggle()
});
$("#closeInput").click(function () {
$('.secondInput').toggle();
$('.secondInput input').val('');
});
});
&#13;
.secondInput {
display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control"/>
<button type="button" id="openInput">Open</button>
<br>
<br>
<div class="secondInput">
<input type="text" class="form-control"/>
<button type="button" id="closeInput">Close</button>
</div>
&#13;
答案 1 :(得分:1)
你必须使用children
方法来find
来自div的输入元素。
.val()
方法主要用于获取表单元素的值,例如input
,select
和textarea
,而不是div
。
children方法获取集合中每个元素的子元素 匹配的元素,可选择由选择器过滤。
另一种方法是直接在选择器中使用它:
$('.secondInput input').val('');
$(function() {
$('#openInput').click(function() {
$('.secondInput').toggle()
});
$("#closeInput").click(function () {
$('.secondInput').toggle();
$('.secondInput').children('input').val('');
});
});
.secondInput{
display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" class="form-control" />
<button type="button" id="openInput">Open</button><br>
<br>
<div class="secondInput">
<input type="text" class="form-control"/>
<button type="button" id="closeInput">Close</button>
</div>
答案 2 :(得分:1)
我向id
元素添加了<input type="text">
个属性,然后将其值设置为''
。
$(function() {
$('#openInput').click(function() {
$('.secondInput').toggle()
});
});
$("#closeInput").click(function () {
$('.secondInput').toggle();
$('#firsttextinput, #secondtextinput').val('');
});
&#13;
.secondInput{
display:none;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input id="firsttextinput" type="text" class="form-control" />
<button type="button" id="openInput">Open</button><br>
<br>
<div class="secondInput">
<input id="secondtextinput" type="text" class="form-control"/>
<button type="button" id="closeInput">Close</button>
</div>
&#13;