开发者

jquery - where to store extra information?

So I've got a plugin I've been working on that takes开发者_开发问答 a select box and then hides it and makes a div with anchor links in it. (The dropdown part and such is working just fine).

When I create the anchor elements, where should I store what option value they represent? When they are clicked, I need to be able to put the data back into the select box.

Ideas? Opinions?


The data function is handy.

// Store
$('#some_selector').data('foo', 'bar');

// Retrieve
var value = $('#some_selector').data('foo');


Two ideas come to mind. First is, don't store the values at all, use the index to select the items:

var realSelect = $("select");
$("#fakeselect").delegate("a", "click", function (e) {
  e.preventDefault();
  realSelect[0].selectedIndex = $(this).index();
});

Or of course, you could also use the jQuery data function to associate the values with the links:

$("option").each( function(i, el) {
   $("<a />", {
     html: el.innerHTML,
     data: { val: $(el).val() }
   }).appendTo("#fakeselect");
});

$("#fakeselect").delegate("a", "click", function (e) {
  e.preventDefault();
  alert( $(this).data('val') ); // alerts value
});


Use an HTML 5 data- attribute.

http://ejohn.org/blog/html-5-data-attributes/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜