如何使用jQuery为select中的每个项添加数据属性[关闭]

I'm trying to create a select drop down, which on change, takes the "data-bg" attribute value of the option, and applies it as the body background.

But the background image urls are coming from somewhere in the php script.

so what i need to do is, take a php array of background image urls, and with a for loop, create a jquery function to add the image urls as data attributes to each option in the select input.

one thing is that the 1st option in the list is a blank, so i will need an offset there too.

What jquery function would i be able to use to loop through the option's in a select to apply a data-attr, so i can bind an on change to change the background image.

let me know if you need any clarification.

See my SUPER DEMO HERE

I believe this is what you want. Use jQuery.each() and onchange() function

I assume that $arr is a PHP array that contains the URLs and that you can include PHP directly in scripts (may need server configuration but easier to write this code inline in your HTML document). I also assume that the select has an id of "my_select".

var arr = <?php echo json_encode($arr); ?>
$("#my_select option").each(function (i, opt) {
    $(opt).attr("data-bg", arr[i]);
});

Use jquery's each() function with a selector for option elements.

$('[name=options]').each(function(index, element) {
    $(element).attr('data-bg', value);
});

Use each function in jquery

[enter link description here][1]

 [Chek the demo here]: http://jsfiddle.net/5aRvF/53/