繁体   English   中英

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

[英]Change multiple span values with select option

我想基于选择框的值更改多个范围值。 请参阅下面的代码。

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();
});

我的控制台说他无法读取undefined的[value]属性。 我的JSON数据不正确吗? 是否应该解析? 还是有人知道这个问题的另一种解决方案。

提前致谢!

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

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

您不应该使用$(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();
});

设置span元素的html内容时,请勿使用$(this) 它看起来应该像这样:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM