我正在尝试将此php函数转换为javascript函数

时间:2013-05-29 15:57:27

标签: 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);

}

1 个答案:

答案 0 :(得分:1)

var parts = [
          club['clubAdd1'],
          club['clubAdd2'],
          club['clubCity'],
          club['clubCounty'],
          club['clubPostcode']
        ];

var address = [];

for (var i=0; i<=parts.length; i++){
    if (parts[i]){
        address.push(parts[i]);
    }
}

var joined = address.join(', ');