简体   繁体   English

使用Java脚本设置HTML属性值

[英]Set HTML attribute value using java Script

I have html drop down list,which has country list. 我有html下拉列表,其中有国家列表。 Now I want to set current country as a default value of list. 现在,我想将当前国家/地区设置为列表的默认值。 I found the JavaScript code for get country using Geolocation. 我找到了使用Geolocation获取国家/地区的JavaScript代码。

My code: 我的代码:

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

Then I need to set the selected attribute of the option list. 然后,我需要设置选项列表的selected属性。

I tried this: 我尝试了这个:

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

But this is not correct. 但这是不正确的。
Basically I want to set selected attribute value using JavaScript function 基本上我想使用JavaScript函数设置选定的属性值

How do I do that? 我怎么做?

Use the window.onload event, and just set the dropdown's value. 使用window.onload事件,只需设置下拉菜单的值即可。 Keep in mind that your hard coded country names may differ from the geo service. 请记住,您的国家/地区代码可能与地理服务有所不同。

<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>

If you are using JQuery following line should solve your problem: 如果您使用的是JQuery,则以下代码行可以解决您的问题:

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

If geoip_country_name returns names in lower case, While initializing the select list, value for each option be in lower case. 如果geoip_country_name以小写形式返回名称,则在初始化选择列表时,每个选项的值geoip_country_name小写形式。

Basically you can do it like this: 基本上,您可以这样做:

<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>

Start the script after your select is rendered. 呈现选择后,启动脚本。

Note, that this example might not be best practice. 请注意,此示例可能不是最佳实践。 I'm also not sure if it works in all browsers (Opera works). 我也不确定它是否适用于所有浏览器(Opera可用)。 You might use an appropriate framework like JQuery, Mootools, ... 您可能会使用适当的框架,例如JQuery,Mootools,...

The selected attribute is not automatically evaluated as JS code. selected属性不会自动评估为JS代码。 Assuming you have stored the desired country name in the variable country , could try this instead: 假设您已将所需的国家/地区名称存储在变量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;
}

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

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