2008-08-26 39 views
5

给定一个在JQuery中有多个选项的选择。使用JQuery将关键值对保存在HTML <select/>中?

$select = $("<select></select>"); 
$select.append("<option>Jason</option>") //Key = 1 
     .append("<option>John</option>") //Key = 32 
     .append("<option>Paul</option>") //Key = 423 

应该如何存储和检索密钥?

该ID可能是一个好地方,但如果我有多个选择的共享值(和其他场景),则不会保证唯一。

感谢

和TMTOWTDI的精神。

$option = $("<option></option>"); 
$select = $("<select></select>"); 
$select.addOption = function(value,text){ 
    $(this).append($("<option/>").val(value).text(text)); 
}; 

$select.append($option.val(1).text("Jason").clone()) 
     .append("<option value=32>John</option>") 
     .append($("<option/>").val(423).text("Paul")) 
     .addOption("321","Lenny"); 

回答

16

像卢卡斯说,价值属性是你需要的。使用你的代码会是这个样子(我添加了一个id属性来选择,使之适合):

$select = $('<select id="mySelect"></select>'); 
$select.append('<option value="1">Jason</option>') //Key = 1 
    .append('<option value="32">John</option>') //Key = 32 
    .append('<option value="423">Paul</option>') //Key = 423 

jQuery的可以让你使用VAL()方法获得的价值。在选择标签上使用它可以获得当前选定选项的值。

$('#mySelect').val(); //Gets the value for the current selected option 

$('#mySelect > option').each(function(index, option) { 
    option.val(); //The value for each individual option 
}); 

为了以防万一,.each方法遍历查询匹配的每个元素。

4

的HTML <option>标签具有所谓的“价值”的属性,在这里你可以存储你的关键。

例如为:

<option value=1>Jason</option> 

我不知道这将如何使用jQuery玩(我不使用它),但我希望这是有益不过。

1

如果您使用的是HTML5,则可以使用custom data attribute。它应该是这样的:

$select = $("<select></select>"); 
$select.append("<option data-key=\"1\">Jason</option>") //Key = 1 
    .append("<option data-key=\"32\">John</option>") //Key = 32 
    .append("<option data-key=\"423\">Paul</option>") //Key = 423 

然后获取所选键,你可以这样做:

var key = $('select option:selected').attr('data-key'); 

或者,如果您使用的是XHTML,那么你就可以创建自定义命名空间。

既然你说钥匙可以重复使用,那么使用value属性可能不是一个选项,因为那样你就无法知道在表单文章中选择了哪个具有相同值的不同选项。

相关问题