使用jQuery在HTML <select>中保持键值对?</select>

时间:2008-08-26 01:46:27

标签: javascript jquery html

在jQuery中给出一个带有多个选项的select。

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

如何存储和检索密钥?

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

由于

并本着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");

3 个答案:

答案 0 :(得分:16)

就像卢卡斯所说,价值属性就是你所需要的。使用你的代码看起来像这样(我在select中添加了一个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()方法获取值。在select标签上使用它可以获得当前所选选项的值。

$( '#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方法遍历查询匹配的每个元素。

答案 1 :(得分:4)

HTML <option>标记有一个名为“value”的属性,您可以在其中存储密钥。

e.g:

<option value=1>Jason</option>

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

答案 2 :(得分:2)

如果您使用的是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属性可能不是一个选项,因为那样你就无法分辨在表单帖子中选择了哪个具有相同值的不同选项。