我在頁面中創建了一對鏈接的選擇框。第二個選擇框填充一組值,具體取決於第一個框的選定值。在鏈式選擇框中應用jquery selectbox風格
使這兩個選擇框像這樣工作的腳本使用PHP和JavaScript。這是我使用的代碼:
形式
<select name="continent" tabindex="1" onChange="getCountry(this.value)">
<option value="#">-Select-</option>
<option value="Europe">Europe</option>
<option value="Asia">Asia</option>
</select>
<div id="countrydiv">
<select name="country" tabindex="2">
<option></option>
</select>
</div>
<input type="submit" />
</form>
JavaScript代碼
$(document).ready(function() {
$('select[name="continent"]').selectbox({debug: true});
$('select[name="country"]').selectbox({debug: true});
});
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCountry(continentId) {
var strURL="findCountry.php?continent="+continentId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('countrydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
PHP代碼(findCountry.php)
<?
$continent=intval($_GET['continent']);
if ($_GET['continent'] == 'Europe') {
?>
<select name="country">
<option value="France">France</option>
<option value="Germany">Germany</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
</select>
<? }
if ($_GET['continent'] == 'Asia') {
?>
<select name="country">
<option value="China">China</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
</select>
<? } ?>
我想要做的是在這些選擇框上應用jQuery選擇框樣式。我還沒有成功做到這一點。問題在於jQuery隱藏了正常的選擇框,並將其替換爲一個列表。此外,在選擇框的內容被刷新後,jquery不能將其重新構建到列表中。你可以看看jQuery代碼here
有什麼我可以做的,以結合這些技術?我嘗試過一百萬件事,但沒有成功。你能幫我麼?
gabriel,非常感謝你的回答。你能提供某種樣品代碼嗎? – zekia 2010-05-12 07:16:12
它的工作原理!非常感謝。我不是一個javascript/ajax專家,這個問題超出了我的理解。非常感謝 – zekia 2010-05-13 13:55:40