我试图在其他帖子中找到问题的解决方案,但找不到类似的东西。
我有这样的html结构:
<p>title abc</p>
<input name="input_a" ... >
<p>title abc</p>
<input name="input_b" ... >
<p>title abc</p>
<input name="input_c" ... >
...
提交表单时,我在Ajax中检查所有字段是否正确填写,如果一切正常,它将返回"success",否则它将返回一个包含未验证字段索引的数组。
例如,如果我只填写"input_b",那么我将获得rs_prod = Array(0, '', 2, 3, ...)
我现在想做的只是将与这些值相关的<p>title abc</p>
涂成红色,添加一个类。
因此,我将每个值rs_prod[index]
与index
:进行比较
$.ajax({
...
success: function(rs_prod) {
if (rs_prod == 'success') {
// success case
} else {
$( rs_prod ).each(function( index ) {
if (index == rs_prod[index]) {
$("#add-form p:eq("+index+")").addClass("redText");
} else {
console.log(index); // never returns 0
$("#add-form p:eq("+index+")").removeClass("redText");
}
});
}
}
事实上,这对我得到的所有错误字段都有效:
<p class= "redText">title abc</p>
在这一点上,当我要填充以前忘记的字段并再次提交时,我应该删除类"redText":这样就发生了。。。它适用于除第一个保持类"redText"的<p>title abc</p>
之外的所有类型,我真的不明白为什么。
我唯一注意到的是,在上面的代码中,console.log(index)
总是返回索引的值,除非该值应该是0。索引似乎以某种方式松动了值0。
编辑/解决方案:
我认为问题主要是由于0,由于某种原因,它没有被认为是值,而是错误的。
这是ajax中用于存储要检查的字段的数组:
$fields_req = array(
0 => 'input1',
1 => 'input2',
2 => 'input3',
3 => 'input4',
...)
我在中更改的
$fields_req = array(
1 => 'input1',
2 => 'input2',
3 => 'input3',
4 => 'input4',
...)
然后按照@Thomas的建议,我更换了
if (index == rs_prod[index]) {
带有
if (rs_prod[index]) {
现在它工作
最后一期:这是我的最终解决方案:
if (rs_prod == 'success') {
// success case
} else {
$("#add-form p").removeClass("redText");
$( rs_prod ).each(function( index ) {
if (rs_prod[index]) {
$("#add-form p:eq("+index+")").addClass("redText");
}
});
这里有一个FIDDLE可能对您有用。
它不包括AJAX调用,但代码的概念可以很容易地转移到AJAX成功或.done函数中。
单击即可读取所有变量并填充数组。
根据输入值的长度(或您可能用于验证的其他条件),输入标签的颜色将更改为红色或蓝色。
我真的不确定你在用ajax做什么,但我相信,如果你第二次点击更新一个或多个变量,你可以回忆起ajax。
也许通过提供更多信息,我们可以为您提供更多帮助。
JS-
var firstarray = [];
$('#clickme').on('click', function(){
$('input').each(function(index){
firstarray[index] = $('input:eq(' + index + ')').val();
console.log(firstarray[index]);
});
console.log( firstarray );
$('p').each(function(index){
if(firstarray[index].length < 1)
{
$('p:eq(' + index + ')' ).css('color', 'red');
}
else
{
$('p:eq(' + index + ')' ).css('color', 'blue');
}
});
});
请检查index
的值,看看它是否以1 or 0
开头。
如果它以1
开始,则增加index
+1并将其用作循环。