0

我有一个 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);

}

4

1 回答 1

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(', ');
于 2013-05-29T16:06:07.997 回答