根据值中的属性键选择选项 [英] Select option base on property key in value

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

问题描述

<option value="abc">abc</option>

我知道我可以做$('select').val('abc'),但是如果我有这样的事情

I know I can do $('select').val('abc') but what if I have something like this

<option value='{"name":abc,"id":123}'>abc</option>

如何基于id选择abc?

推荐答案

value不是有效的对象. abc应该用引号引起来.

The value is not a valid Object. abc should be wrapped in quotes.

<option>应该是

<option value='{"name":"abc","id":123}'>abc</option>
                       ^   ^

您可以使用> filter() 过滤出具有在value属性类似对象的字符串中,id为123.

You can use filter() to filter out the <option> elements which are having the id as 123 in the value attribute object-like string.

然后, prop('selected', true) 可以在过滤后的option上使用以设置为选中状态选项.

Then, prop('selected', true) can be used on the filtered option to set as selected option.

演示:

// Filtering all options in the select
$('select option').filter(function() {
    var val = $(this).val(), // Get value
        obj = {};

    // Try to parse the string to JSON
    try {
        obj = JSON.parse(val);
    } catch (e) {
        obj = {}; // Empty object if parsing fails
    }

    // Filter based on the `id` in the value
    return obj.id === 123;
}).prop('selected', true); // Set the option as selected

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
    <option value="Hello">fdsafds</option>
    <option value='{"name":"abc","id":123}'>abc</option>
</select>

由于人造丝具有

As Rayon has commented, instead of using object as the value, I'll recommend to use HTML5 data-* custom attributes to store data on element.

$('option[data-id="123"]').prop('selected', true);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select>
    <option value="Hello" data-name="bond" data-id="007">fdsafds</option>
    <option value="something" data-name="abc" data-id="123">abc</option>
</select>

这篇关于根据值中的属性键选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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