我有一个“添加访客”(添加输入)按钮,当用户点击它时,它下面会出现一个新输入。我的问题是,如果用户填写输入并单击“添加访客”按钮,他们在第一个输入中键入的内容将被删除。
有没有办法保留我的功能,但保留输入中的内容,同时还要添加新功能?
link.label
$('#addGuest').click(function() {
var count = $('.guestName').length;
document.getElementById('guestWrap').innerHTML += '<div class="formField guestName" id="guestName' + (count + 1) + '"><label class="label">What is your guest\'s name?</label><input type="text" class="input" name="guest' + (count + 1) + '" id="guest' + (count + 1) + '"></div>';
$('.guestName').fadeIn(400);
});
.formField {
margin-bottom: 40px;
}
.label {
font-family: 'Quicksand', sans-serif;
font-size: 1.2rem;
line-height: 1.5em;
margin: 20px 0;
display: block;
}
.input {
font-family: 'Open Sans', sans-serif;
font-size: .9rem;
display: block;
width: 60%;
padding: 15px 10px;
text-align: center;
margin: 0 auto;
outline: none;
-webkit-transition: 1s;transition: 1s;
}
#guestWrap {
height: auto;
}
答案 0 :(得分:3)
当您分配元素的innerHTML
时,当前元素将被销毁;清空容器,只保留原始HTML字符串。因此,容器内任何元素的当前value
都将丢失。请改用insertAdjacentHTML
,而不取消引用现有元素:
$('#addGuest').click(function() {
var count = $('.guestName').length;
document.getElementById('guestWrap').insertAdjacentHTML('beforeend', '<div class="formField guestName" id="guestName' + (count + 1) + '"><label class="label">What is your guest\'s name?</label><input type="text" class="input" name="guest' + (count + 1) + '" id="guest' + (count + 1) + '"></div>');
$('.guestName').fadeIn(400);
});
.formField {
margin-bottom: 40px;
}
.label {
font-family: 'Quicksand', sans-serif;
font-size: 1.2rem;
line-height: 1.5em;
margin: 20px 0;
display: block;
}
.input {
font-family: 'Open Sans', sans-serif;
font-size: .9rem;
display: block;
width: 60%;
padding: 15px 10px;
text-align: center;
margin: 0 auto;
outline: none;
-webkit-transition: 1s;transition: 1s;
}
#guestWrap {
height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="guestWrap">
<div class="formField guestName" id="guestName">
<label class="label">What is your guest's name?</label>
<input type="text" class="input" name="guest1" id="guest1">
</div>
</div>
<div id="addGuest">
<span class="guestIncrease">Add another guest</span>
</div>