0

This question has been asked before, but most of the answers revolve around HTML5.

My DOCTYPE is:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

I need to attach data (phone dialling code) to option values of a select:

<select id="id_creditCardCountry">  
<option value="ax">Aland Islands - AX</option> 
<option value="al">Albania - AL</option> 
<option value="dz">Algeria - DZ</option><!--e.g. Attach dial code "(+213)" -->
<option value="as">American Samoa - AS</option>
<option value="ad">Andorra - AD</option>
<option value="ai">Anguilla - AI</option>
etc

There seem to be numerous ways to accomplish this. I need to find the best one (by best I mean most cross browser and efficient).

  • The jQuery "data" function http://docs.jquery.com/Core/data -- if this is the best method, can anyone give guidance of how to use in this instance?
  • Set data based on element ID - This involves having to give an id to every option in the select.
  • Further suggestions?
4

1 回答 1

1

你可以使用:

$("#id_creditCardCountry option[value='ax']").data("dial-code", "+213");

如果你有一个包含所有国家和拨号代码的 JS 数组,那么你可以遍历它们:

for(var i = 1; i <= countryArray.length; i++){
    $("#id_creditCardCountry option[value='"+countryArray[i]+"']").data("dial-code", ""+dialCodeArray[i]+"");
}

但是,如果您已经在输出国家/地区列表,则可能需要考虑在服务器端执行此操作。例如:

<option value="ax" data-dial="+213">Aland Islands - AX</option> 
于 2013-04-18T10:19:48.857 回答