下面的代码工作正常,但它是硬编码的。我希望能够创建一个字段集数组,隐藏这些字段,然后每次单击“#createEventForm-eventInformation-addElement”按钮时它都会显示下一个。以下代码的问题在于它是硬编码的,因此很容易中断并且比使用循环要大得多。谁能帮我把它做得更好。
$("#fieldset-group1").hide();
$("#fieldset-group2").hide();
$("#fieldset-group3").hide();
$("#fieldset-group4").hide();
$("#fieldset-group5").hide();
$("#fieldset-group6").hide();
$("#fieldset-group7").hide();
$("#fieldset-group8").hide();
$("#fieldset-group9").hide();
$("#createEventForm-eventInformation-addElement").click(
function() {
ajaxAddEventInformation();
if($("#fieldset-group1").is(":hidden"))
{
$("#fieldset-group1").show();
}
else
{
$("#fieldset-group2").show();
}
}
);
最佳答案
您应该使用 jquery 选择器的 ^= 表示法,这意味着开始于 ..
// this will hide all of your fieldset groups
$('[id^="fieldset-group"]').hide();
然后
$("#createEventForm-eventInformation-addElement").click(
function() {
ajaxAddEventInformation();
// find the visible one (current)
var current = $('[id^="fieldset-group"]:visible');
// find its index
var index = $('[id^="fieldset-group"]').index( current );
// hide the current one
current.hide();
// show the next one
$('[id^="fieldset-group"]').eq(index+1).show();
}
);
关于javascript - 循环遍历 javascript 改进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2135109/