我有两个主要部分 intro-info
和 current-info
。我基本上希望他们做同样的事情,但在不同的时间展示。在页面加载时,首先显示 intro-info
容器,然后您浏览并填写输入,然后单击继续。我想不通的是如何显示 current-info
容器,但在单击按钮后隐藏除第一个输入以外的所有输入。
我使用 .hide()
隐藏第一个容器 intro-info
,然后使用 show()
显示它。像这样:
$('#intro-button').click(function(){
$('#intro-info').hide(200);
setTimeout(function(){
$('#current-info').show(500);
}, 300);
});
在显示行中,我尝试执行 $('.current)
、$('.current:first-child)
,但是当我这样做了,理想情况下我希望整个容器出现以供将来添加,但只需隐藏第一个以外的所有输入。
Here is a fiddle to show you what I mean ... 同样,在您点击继续之后,一旦所有输入都已填写,您将看到 section 部分进入 View 并且有多个输入。有人看到我能做什么吗?
最佳答案
正如我在评论中所说,我不会创建复制/粘贴 - 意大利面条代码,
相反,我会坚持更好的逻辑:
删除那些无用的 ID 和多余的类。使用一些逻辑,例如: 1. 一个父级有一个继续按钮 - 单击显示下一个父级元素。 2. 每个输入都使下一个输入出现在同一个父级中。
jQuery(function( $ ) { // DOM is now ready
// Group your logic by parents!
$(".labelsGroup").each(function() {
var $thatGroup = $(this);
var $nextGroup = $thatGroup.next(".labelsGroup");
var $inputs = $thatGroup.find("input");
var $proceed = $thatGroup.find("button");
$inputs.on("input", function(){
var $nextLabel = $(this).closest("label").next("label");
if($.trim(this.value).length > 3) {
$nextLabel.has(":input").addClass("show");
}
});
$proceed.on("click", function(e){
e.preventDefault(); // Don't submit <form> (if any is used)
var allValid = $inputs.filter(function() {
return $.trim(this.value).length > 3;
}).length === $inputs.length;
// TODO: use a better validation plugin than the above
if(allValid) { // Finally proceed!!
$thatGroup.addClass("hide");
$nextGroup.addClass("show");
// TODO: Submit form using AJAX to a service
} else { // or Log error!!
return alert("Please fill-in the missing fields!");
}
});
});
});
.labelsGroup {
text-align: center;
}
.labelsGroup label {
display: block;
margin: 20px 0;
}
.labelsGroup label input {
background: #fff;
padding: 10px 15px;
border: 1px solid #999;
}
/* hide all but first label in parent */
/* hide all subsequent labelsParents */
.labelsGroup label + label,
.labelsGroup + .labelsGroup,
.hide {
opacity: 0;
visibility: hidden;
position: absolute;
}
.show {
opacity: 1 !important;
visibility: visible !important;
position: relative !important;
-webkit-transition: opacity 0.7s ease-in;
transition: opacity 0.7s ease-in;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="labelsGroup">
<label>
What is your name?<br>
<input name="name" type="text"><!-- PS: use name="" instead of id=""-->
</label>
<label>
What is your email address?<br>
<input name="email" type="email">
</label>
<label>
<button>Proceed</button>
</label>
</div>
<div class="labelsGroup">
<label>
Do you have<br>
<input name="have" type="text">
</label>
<label>
What is your current<br>
<input name="what_is_your" type="text">
</label>
<label>
<button>Proceed</button>
</label>
</div>
关于javascript - 使用步骤/组创建表单的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38859707/