开发者

Is there a way to attach a Javascript object to a Select Option

When building up a list of options in a select list using Javascript I'd like to attach a Javascript object to that option that I could easily retrieve in the change event.

So, while writing this question I wanted to provide some sample code and found a way to make this work; so I have a slight addition to the question. Is it bad to attach javascript object to DOM elements? Back in the day I remember there being issues with memory leaks in certain circumstances.

Here's a working example: http://jsbin.com/afolo3/edit

var objs = [
  { id: 1, value: "One", type: "number" },
  { id: 2, value: "Two", type: "number" },
  { id: 3, value: "Three", type: "number" },
  { id: "A", value: "A", type: "char" },
  { id: "B", value: "B", type: "char" },
  { id: "C", value: "C", type: "char" },
  ];

var options = $.map(objs, function(item, idx) {
  var opt = $("<option/>").val(item.id).text(item.value);
  opt[0]["obj"] = item;
  return opt;
});

$.fn.appen开发者_StackOverflowd.apply($("#select"), options)
  .change(function() {
    $("#select option:selected")
      .each(function(){
    alert(this.obj.type);
      });
  });


Use jQuery's .data() function instead.

Updated example: http://jsbin.com/afolo3/2


You can certainly attach objects to element instances the way you have; in fact, that's how jQuery does its data magic behind-the-scenes in the current version.

That said, since you're using jQuery already, I'd probably use the jQuery API for this (data) instead, just in case it turns out that at some stage, a browser comes on the scene where a workaround is required — you'll get the benefit of the jQuery maintainers doing the workaround for you, rather than having to do it yourself.

Here's what it would look like using data. Basically to set the data:

opt.data("obj", item);

...and to retrieve and show its type property:

alert(opt.data("obj").type);

...where in each case, opt is a jQuery object for the option element in question.

One slight "gotcha" with jQuery's data function: If you retrieve a data object you've never set, you'll get null back (rather than undefined, which would be the usual JavaScript convention).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜