关于 select 和 option value="" 的问题使用 JQuery

发布于 2024-08-10 16:53:22 字数 760 浏览 4 评论 0 原文

假设我的列表如下所示:

<select name="name" id="id">
    <option value="10176232332">David</option>
    <option value="10187232332">Sven</option>
    <option value="10202232332">Ololf</option>
    <option value="10219232323">Jan</option>
    <option value="10230232323">Gustaf</option>
</select>

使用 JQuery,我如何提取每个选项的值 - 例如:

<option value="10176232332">David</option>

其中 10176232332 是值。使用:

($("#id").val()) 

提取名称,而不是数字组合。使用 regluar Javascript 我会使用:

list.options[list.selectedIndex].value;

有没有一种“JQuery 方式”可以做到这一点,或者我应该坚持上面的方法?

预先感谢您的任何帮助。

let's say i have list looking like this:

<select name="name" id="id">
    <option value="10176232332">David</option>
    <option value="10187232332">Sven</option>
    <option value="10202232332">Ololf</option>
    <option value="10219232323">Jan</option>
    <option value="10230232323">Gustaf</option>
</select>

Using JQuery, how can i extract the value for each option - for example:

<option value="10176232332">David</option>

Where 10176232332 is the value. Using:

($("#id").val()) 

extracts the names, not the number combinations. Using regluar Javascript i would use:

list.options[list.selectedIndex].value;

Is there a "JQuery way" of doing that or should i stick to the above?

Thanks in advance for any help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

沉鱼一梦 2024-08-17 16:53:22
var selected = $("#id option:selected");
var value = selected.val();
var selected = $("#id option:selected");
var value = selected.val();
九命猫 2024-08-17 16:53:22

val() 函数仅适用于 input 元素(inputselecttextarea按钮)。 option 元素不是输入元素。

如前所述,您需要将其视为“普通”元素,通过 option.attr('value') 获取它。

The val() function only works for input elements (input, select, textarea, button). The option element is not an input element.

As said before, you need to handle it as a "normal" element, get it by option.attr('value').

空心↖ 2024-08-17 16:53:22

我认为这应该可行:

$("#id").attr("value")

...但是自从我使用 jQuery 以来已经有一段时间了。

I think this should work:

$("#id").attr("value")

...but it's been a while since I used jQuery.

荒人说梦 2024-08-17 16:53:22

我假设您将触发事件处理程序来捕获此信息,对吗?如果是这样,我将如何访问选定值的“id”和“name”组件:

    $('select').change(function () { 
        var id = $(":selected", this).val();
        var name = $(":selected", this).text();
    });

`
此处有此代码的演示。

I'm assuming you will be triggering an event handler to capture this information, correct? If so, here is how I would access a selected value's "id" and "name" components:

    $('select').change(function () { 
        var id = $(":selected", this).val();
        var name = $(":selected", this).text();
    });

`
There is a demo of this code in action here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文