2017-06-29 111 views
0

從這個jQuery代碼開始:遺漏的類型錯誤:無法讀取空的特性 '追加' jQuery中

var country_name_list=document.getElementById("country");    
$.post(getcountry,function (data) { 
    var Rcountry_name_list=JSON.parse(data); 
    var arr=[]; 
    for(var i=0;i<Rcountry_name_list.countries.length;i++){ 
     var r_id=Rcountry_name_list.countries[i].country_id; 
     var r_name= Rcountry_name_list.countries[i].country_name; 
     var option_name = document.createElement("option"); 
     option_name.textContent =r_name; 
     option_name.value = r_id; 

     country_name_list.append(option_name);  
    } 

}); 

HTML

<form method="post" action="" id="rform" novalidate="novalidate"> 
    <label class="control-label">Country </label> 
    <select id="country" name="country" class="form-control" > 
     <option value=" " disabled selected hidden>Select Country</option> 
     <option value="0"></option> 
    </select> 
</form> 

上線country_name_list.append(option_name);我收到以下錯誤

Uncaught TypeError: Cannot read property 'append' of null in jQuery

+0

您能不能告訴JSON響應? –

+0

既然你沒有發佈任何內容,爲什麼不使用$ .get? –

+0

@TonySamperi'country_name_list'爲'null'的問題在哪裏? – Andreas

回答

1

首先,當一個DOM選擇符返回null時,它表示找不到該元素。所以你必須等待DOM被加載。

使用jQuery它足以在下面的語句

$(document).ready(function(){ 

}); 

vi5ion的權利來包裝你的選擇,但你也可以提高你的代碼

var country_name_list = document.getElementById("country");  

Here you didn't use jQuery, so you have to keep using javascript DOM methods.

$.get(getcountry, function (data) { 

Here $.get is enough

var response = JSON.parse(data); 

I think Capital letter is only for classes

var option, current; 

If you create the variables here, you avoid creating a new variable for each loop, so will save time!

var list = response.countries; 
    for(var i=0; i < list.length; i++){ 
     current = list.countries[i]; 
     option = document.createElement("option"); 
     option.textContent = current.country_name; 
     option.value = current.country_id; 
     country_name_list.appendChild(option_name); 

As vi5ion suggests appendChild() is what you need

 } 

}); 

似乎現在更容易閱讀的代碼,不是嗎? 希望這是有用的!

0

country_name_list不是jQuery對象,因此沒有append()函數。

事實上,你的大部分代碼都是普通的JavaScript而不是jQuery,所以你可能會想使用函數appendChild()來代替。

編輯:添加下面

替代jQuery的解決方案如果你堅持使用jQuery你可以換你的變量。
這既可以在這裏完成

var country_name_list = $('#country'); 

或這裏

$(country_name_list).append(option_name); 

但不能同時使用。

+0

根據瀏覽器的不同,還有一個「native」'.append()'方法可用:['ParentNode.append()'](https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append)/ http://caniuse.com/#feat=dom-manip-convenience – Andreas

+0

哦,我其實不知道。儘管如此,在IE中缺乏支持對大多數人來說仍是一個難題。 – vi5ion

0

當您收到類型爲「無法讀取null屬性XXX」的錯誤時,您需要確保在調用腳本時存在元素。例如,您可以將JavaScript放在結束標記之前,以確保該元素在DOM中。

另外,如果你在頭插入你的腳本,在頁面中或之前,你可能要附上我的$。就緒()方法中,以確保其只運行後的DOM就緒

$(document).ready(function() { 
    ... your code 
} 

你可以找到更多信息:https://api.jquery.com/ready/

相關問題