2017-01-23 13 views
-1

在陣列當我<code>exist_id</code>數組值是<code>null</code>的<code>if</code>條件的作品並不if語句工作,在JavaScript

val = this.value 

$(document).ready(function() { 
    $('.all_id_checkbox').click(function() { 
     var a = this.checked; 
     if (a == true) { 
      exist_id = new Array(); 
      exist_id = <?php echo json_encode($exist); ?>; 
      val = parseInt(this.value); 

      if (jQuery.inArray(val, exist_id)) { 
       exist_error.push(val); 
      } else { } 
     } 
    }); 
}); 
+1

什麼是'$ exist'的價值?或者更好 - 在輸出PHP之後,你的實際JS代碼是什麼?我猜想,'exist_id'將是一個對象,因此'$ .inArray'無效使用 –

+0

'$(文件)。就緒(函數(){ $( 'all_id_checkbox')。點擊(函數( ){ VAR一個= this.checked; 變種VAL = parseInt函數(THIS.VALUE); 條件:(a == TRUE){ VAR exist_error = []; 變種exist_id = ; 變種new_array = Object.values(exist_id); 如果(jQuery.inArray(VAL,new_array)){ exist_error.push(VAL); }否則{} } });} ) ;' –

回答

0

如果exist_id是一個對象是正常的jQuery.inArray()不工作; inArray檢查值數組是否包含值,因此無法檢查鍵值對(json)。

(你應該向我們展示的console.log(exist_id)輸出開始)。

反正你要分配的json_encode()返回exist_id但正如你可能知道JSON的意思是「JavaScript對象符號」這樣的json_encode回報率將是「對象符號」因此,當你把它分配給exist_id它變成一個JavaScript對象。

因此很明顯jQuery.inArray不起作用。

爲了它只是工作,通過它你的對象的值,而不是JSON(鍵值對):

if (jQuery.inArray(val, Object.values(exist_id))) 

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/values

順便說一句,我看到你有一個在JavaScript至極PHP的標籤意味着你正在使用內聯scripts.This是一種不好的做法。什麼,你應該做的是:

把數據在數據屬性的html元素:

<div id="exist-id" data-ids="<?php echo json_encode($exist); ?>"></div> 

然後在外部JS腳本獲取的價值:

$('#exist_id').data('ids'); 

https://api.jquery.com/data/