jQuery按值选择选项元素 [英] jQuery select option elements by value

查看:115
本文介绍了jQuery按值选择选项元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由span元素包裹的select元素。我不允许使用select id但我可以使用span id。
我正在尝试编写一个javascript / jquery函数,其中输入是数字i,这是select选项的值之一。该功能会将相关选项变为选中状态。

I have a select element wrapped by a span element. I am not allowed to use the select id but I am allowed to use the span id. I am trying to write a javascript/jquery function in which the input is a number i, which is one of the values of the select's options. The function will turn the relevant option to selected.

<span id="span_id">
    <select id="h273yrjdfhgsfyiruwyiywer" multiple="multiple">
        <option value="1">cleaning</option>
        <option value="2">food-2</option>
        <option value="3">toilet</option>
        <option value="4">baby</option>
        <option value="6">knick-knacks</option>
        <option value="9">junk-2</option>
        <option value="10">cosmetics</option>
    </select>
</span>

我写了如下内容(这不完全有效,这就是我发布这个问题的原因) :

I wrote something as follows (this does not completely work, which is why I am posting this question):

function select_option(i) {

    options = $('#span_id').children('select').children('option');
    //alert(options.length); //7
    //alert(options[0]); //[object HTMLOptionElement]
    //alert(options[0].val()); //not a jquery element
    //alert(options[0].value); //1

    //the following does not seem to work since the elements of options are DOM ones not jquery's
    option = options.find("[value='" + i + "']");
    //alert(option.attr("value")); //undefined
    option.attr('selected', 'selected');

}

谢谢!

推荐答案

以下是带有清晰选择器的最简单的解决方案:

Here's the simplest solution with a clear selector:

function select_option(i) {
  return $('span#span_id select option[value="' + i + '"]').html();
}

这篇关于jQuery按值选择选项元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆