使用选择选项更改多个跨度值

时间:2015-02-26 08:59:37

标签: javascript jquery html

我想根据选择框的值更改多个跨度值。请参阅下面的代码。

HTML:

<select id="selectCountry">
  <option value="0">Netherlands</option>
  <option value="1">Germany</option>
  <option value="2">Switzerland</option>
</select>

使用Javascript / jQuery的

var addressData = [{"addressName": "Spiegelhof", 
          "addressStreet": "Herengracht 466", 
          "addressCity": "1017 CA Amsterdam", 
          "addressCountry": "the Netherlands", 
          "countryOne": "Netherlands", 
          "countryTwo": "Belgium", 
          "phoneOne": "+31 20 658 9800",
          "phoneTwo": "+32 2 588 12 77",
          "code": "NL"},
         {"addressName": " ", 
          "addressStreet": " ", 
          "addressCity": "Munchen", 
          "addressCountry": "Deutschland", 
          "countryOne": "Germany", 
          "countryTwo": "Switzerland", 
          "phoneOne": " ",
          "phoneTwo": " ",
          "code": "DE"}];


$(document).ready(function() {
$("#selectCountry").change(function() { 
    var value = $('#selectCountry').val();
    $('#addressName').html($(this).addressData[value].addressName);
    $('#addressStreet').html($(this).addressData[value].addressStreet);
    $('#addressCity').html($(this).addressData[value].addressCity);
    $('#addressCountry').html($(this).addressData[value].addressCountry);
}).change();
});

我的控制台是他无法读取未定义的[value]属性。我的JSON数据不正确吗?它应该被解析,如果是,如何解析?或者有人知道这个问题的另一种解决方案。

提前致谢!

3 个答案:

答案 0 :(得分:2)

在您的示例中,addressData是全局范围内的数组,而不是jquery元素$(this)的属性。试试这个:

$('#addressName').html(addressData[value].addressName);
$('#addressStreet').html(addressData[value].addressStreet);
$('#addressCity').html(addressData[value].addressCity);
$('#addressCountry').html(addressData[value].addressCountry);

答案 1 :(得分:2)

您不应该使用$(this)来阅读addressData,因为$(this)引用selectCountry选择框,将其删除。

$(document).ready(function() {
$("#selectCountry").change(function() { 
    var value = $('#selectCountry').val();
    $('#addressName').html(addressData[value].addressName);
    $('#addressStreet').html(addressData[value].addressStreet);
    $('#addressCity').html(addressData[value].addressCity);
    $('#addressCountry').html(addressData[value].addressCountry);
}).change();
});

答案 2 :(得分:1)

在设置$(this)元素的html内容时,不应使用span。看起来应该是这样的:

$('#addressName').html(addressData[value].addressName);