我試圖找到我的問題在其他帖子的解決方案,但我找不到類似的東西。比較數組值和索引值在每個()jquery
我有這個網站結構:
<p>title abc</p>
<input name="input_a" ... >
<p>title abc</p>
<input name="input_b" ... >
<p>title abc</p>
<input name="input_c" ... >
...
提交我在阿賈克斯檢查所有字段填寫正確的形式,如果一切順利,將返回「成功」,否則它會返回一個數組包含未驗證字段的索引。
例如,如果我填表的只有「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'刪除:所以它會發生......除了第一個<p>title abc</p>
保留課程'redText'和我不明白爲什麼。
我注意到的唯一的事情就是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");
}
});
而不是'如果(指數== rs_prod [指數]){...}','嘗試如果(rs_prod [指數]){...}' – 1252748 2014-09-11 01:37:00
爲什麼不你發回無效條目的字段名稱嗎?少得多的猜測工作 – charlietfl 2014-09-11 01:40:11
當執行'console.log(rs_prod)'時,'rs_prod'看起來像什麼? (對於不成功的案例。) – flowstoneknight 2014-09-11 01:56:59