用纯文本替换变量值,如果值不可用则忽略它

时间:2010-10-29 02:56:50

标签: javascript ruby-on-rails

我有以下javascript代码:

function append_place(street, city, state, country) {
      var address = street + ', ' + city + ', ' + state + ', ' + country;
      $(".shop_location").append(address);

streetcitystatecountry是从数据库中提取的外部变量。 (顺便说一句,我正在开发Ruby on Rails项目。)

理想情况下,当从数据库中找到所有值时,HTML中的输出将为:

<div class="shop_location">3 Spencer St, Melbourne, Victoria, Australia</div>

但是,当state在数据库中没有值时,HTML中的输出将为:

<div class="shop_location">3 Spencer St, Melbourne, , Australia</div>

如何在Javascript中写入当值为空时,它将被其他值替换,甚至更好,省略它。 state没有值时的理想输出是:

<div class="shop_location">3 Spencer St, Melbourne, Australia</div>

对于某些其他功能,如果找不到该值,我可能希望显示“不可用”。

当然在Ruby on Rails中,我可以在视图中使用if-else语句来替换文本。

非常感谢!

2 个答案:

答案 0 :(得分:1)

我不知道javascript,但我经常在rails帮助器中做这种事情:

[street, city, state, country].compact.join(', ')

如果条目为nil,则可行,但如果有空字符串"",则使用此字符:

[street, city, state, country].reject(&:blank?).join(', ')

答案 1 :(得分:0)

怎么样:

function append_place(street, city, state, country) {
  var a = new Array();
  if (street.length > 0) a.push(street);
  if (city.length > 0) a.push(city);
  if (state.length > 0) a.push(state);
  if (country.length > 0) a.push(country);

  var address = a.join(', ');
  $(".shop_location").append(address);
}