尝试使用jQuery在选定选项中的数组中找到数据值,找到它时,我想添加一个属性,因为它们是选项标记和选定属性。
这看起来很容易,但实际上并非如此。
我的代码如下:
function selected_element() { var association = $("#association").children("option").map(function() { return this.value; }).get(); var ass_val = $("#association").children("option"); console.log(ass_val, association); var ass_data = $("#association").children("option").attr('data-selected'); console.log(ass_data ); if (ass_val == ass_data) { $("#association").children("option").val(ass_data).attr("selected","selected"); } }; selected_element();这仅仅是一个例子:
我的第一行将映射我的数组,所以我返回值(1,2,3,4)。
我的第二行将返回选项和值,但我不能对他们做很多事情。
我的ass_data实际上是我用来在这种情况下检索数据标签的数组(数据选择)。
我最后一行代码仅仅是我想要实现的一个例子:
if (ass_val == ass_data) { $("#association").children("option").val(ass_data).attr("selected","selected"); } };它不会工作,只是为了展示我的想法。
Try to find a data-value in an array in a selected option with jquery, and when find it, I want to add an attribute, since they're an option tag, a selected attribute.
It seems pretty easy but actually it is not.
My code is the following:
function selected_element() { var association = $("#association").children("option").map(function() { return this.value; }).get(); var ass_val = $("#association").children("option"); console.log(ass_val, association); var ass_data = $("#association").children("option").attr('data-selected'); console.log(ass_data ); if (ass_val == ass_data) { $("#association").children("option").val(ass_data).attr("selected","selected"); } }; selected_element();This is just an example:
My first line will map my array, so I return the value (1,2,3,4).
My second line will return both options and values, but I can't do really a lot with them.
My ass_data is actually the array that I'm using to retrieve the data tag in this case (data-selected).
My last line of code is just an example of what I wish to achieve:
if (ass_val == ass_data) { $("#association").children("option").val(ass_data).attr("selected","selected"); } };It won't work, is just to display my idea.
最满意答案
假设这些值是唯一的,您可以为下拉列表添加一个事件侦听器,然后find() :selected option :
$("#association").on("change", function () { var t = $(this), val = t.val(); if (val) { // filter out empty/null values as possible matches t.find(":selected").attr({<put attribute name here> : <attribute value here>}); // for example // t.find(":selected").attr({"data-selected" : true}); } });Assuming the values are unique you could just add an event listener for the dropdown and then find() the :selected option:
$("#association").on("change", function () { var t = $(this), val = t.val(); if (val) { // filter out empty/null values as possible matches t.find(":selected").attr({<put attribute name here> : <attribute value here>}); // for example // t.find(":selected").attr({"data-selected" : true}); } });更多推荐
发布评论