jQuery - 从值数组中按值选择元素 [英] jQuery - Select elements by value from array of values

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

问题描述

给出一些简单的JSON:

Given some simple JSON:

["62689", "62690", "62697"]

我需要选择DOM中与这些值对应的三个元素(基于 value 属性)。它们可以是< select> < input> < option> 或其他任何东西。

I need to select the three elements in the DOM that correspond to these values (based on value attribute). They could be a <select>, <input>, <option> or anything really.

我应该使用哪个选择器?

What selector should I be using for this?

推荐答案

你可以使用jQuery的属性等于选择器

You can use jQuery's Attribute Equals Selector.


选择具有指定属性的元素,其值完全等于某个值。

例如,要选择 62689 的元素,您将使用:

For example to select the element whose value is 62689, you'd use:

$('[value="62689"]')

要选择全部三个,您可以使用:

To select all three, you'd use:

$('[value="62689"], [value="62690"], [value="62697"]')

如果你想对这些元素应用一些方法,并且你有多于或少于这三个值,你可以循环你的JSON响应并相应地应用:

If you want to apply some method to these elements and you have more or less than those exact three values, you can just loop through your JSON response and apply accordingly:

var data = ["62689", "62690", "62697"];

for (var i = 0; i < data.length; i++)
    $('[value="' + data[i] + '"]');

或者你可以使用 jQuery的 map()方法

Or you can just pull them all into an array using jQuery's map() method:

var elements = $('input, select').map(function() {
    if ($.inArray(this.value, data) != -1)
        return this;
    return false;
}).get();

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

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