我有一個PHP函數來從數據庫檢索到的數據創建一個地址。我想要使用相同的功能來創建一個JavaScript函數來執行相同的操作。它所做的是採取領域,如果它是空的,它什麼都不做,但如果有數據,它會附加「,」一個逗號和空格。我想把這個php函數轉換成javascript函數
$parts = array(
$club['clubAdd1'],
$club['clubAdd2'],
$club['clubCity'],
$club['clubCounty'],
$club['clubPostcode'],
);
$address = array();
foreach ($parts as $part){
if ('' != $part){
$address[] = $part;
}
}
$address = implode(', ', $address);
我的當前的嘗試是每次被調用的函數的KEYUP上表單字段預成形(測試目的)
function autoAddress(){
var address = "";
var address1 = document.address.address1.value;
var address2 = document.address.address2.value;
var city = document.address.city.value;
var county = document.address.county.value;
var postcode = document.address.postcode.value;
var parts = new array[
address1,
address2,
city,
county,
postcode
];
var testAddress = new array();
foreach(parts as part){
if ('' != part){
testAddress[] = part;
}
}
testAddress = array.join(', ', testAddress);
alert(testAddress);
}
JavaScript使用[Array.join] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join)來執行PHP中的'implode'功能。否則,只需使用'+'連接字符串 – Blazemonger
我不是100%確定的,但我認爲你的最後一個變量不需要逗號。 '$ club ['clubPostcode'],'嘗試刪除逗號。 –
到目前爲止你的嘗試是什麼?我沒有看到任何JavaScript代碼 – rednaw