使用javaScript设置HTML属性值

时间:2012-12-18 07:11:42

标签: javascript html

我有html下拉列表,其中包含国家/地区列表。现在我想将当前国家/地区设置为列表的默认值。我找到了使用Geolocation获取国家/地区的JavaScript代码。

我的代码:

function getCountry(var name) {
    if(name==geoip_country_name()) {
        return "selected";
    }
}

然后我需要设置选项列表的selected属性。

我试过了:

<option value="Sri Lanka" selected="getCountry('sri Lanka')">Sri Lanka</option>

但这不正确。
基本上我想使用JavaScript函数

设置选定的属性值

我该怎么做?

4 个答案:

答案 0 :(得分:4)

使用window.onload事件,只需设置下拉列表的值即可。请注意,您的硬编码国家/地区名称可能与地理位置服务不同。

<script>
    window.onload = function(){
        document.getElementById("country").value = geoip_country_name();
    }
</script>

<select id="country" name="country">
<option value="Sri Lanka">Sri Lanka</option>
<option value="UK">UK</option>
<option value="USA">USA</option>
<select>

答案 1 :(得分:0)

如果您正在使用JQuery,则应该解决您的问题:

$('select').val(geoip_country_name());

如果geoip_country_name以小写形式返回名称,则在初始化选择列表时,每个选项的值均为小写。

答案 2 :(得分:0)

基本上你可以这样做:

<html>
<body>
  <select id="country">
  <option id="germany" value="Germany">DE</option>
  <option id="uk" value="UK">UK</option>
  <option id="usa" value="USA">USA</option>
</select>
<script>
  var selectedCountry =  'uk'; //getCountry
  var index = document.getElementById(selectedCountry).index;
  document.getElementById("country").selectedIndex=index;
</script>

渲染选择后启动脚本。

请注意,此示例可能不是最佳做法。我也不确定它是否适用于所有浏览器(Opera工作)。您可以使用适当的框架,如JQuery,Mootools,......

答案 3 :(得分:0)

selected属性不会自动评估为JS代码。假设您已在变量country中存储了所需的国家/地区名称,可以尝试使用此选项:

var country = "Sri Lanka";
var select = document.getElementById('myselect'); //Change to the ID of your select element
for (var i = 0; i < select.options.length; i++){
    if(select.options[i].value == country)
        select.selectedIndex = i;
}