开发者

jQuery html element attribute names

I was asked to help add an onChange to a select so I came up wit开发者_Python百科h this:

$("select[name=component]").change(function() {
  $("input[name=Code]").val(JSONObject[$(this).selectedIndex].code;  
  $("input[name=Category]").val(JSONObject[$(this).selectedIndex].category;  
  $("input[name=UOM]").val(JSONObject[$(this).selectedIndex].uom;  
});

The asker told me it didn't work until he changed $(this) to this

That only makes sense to me, if jQuery does not use the name selectedIndex of what I assume is a jQuery object.

If not, would I just need to use .attr("selectedIndex")?

Is jQuery converting the object on the fly from $(this) (jQuery object) to a form element or select object?


The jQuery object is not really an extension of the DOM element: The DOM element becomes a child of the jQuery one.

It is in the 0 member of the jQuery object, so if for some reason one needs to use the jQuery object (which as @nickf in the context of this example is insane - you would just use this.selectedIndex instead), one would have to use

$(this)[0].selectedIndex

to access the original attribute.


Inside of all the event handlers, this is the DOM Element itself and is not a jQuery object.

There's no magic here - $(this) simply creates a jQuery object wrapped around your element (the <select>). jQuery doesn't have a .selectedIndex property, but the DOM Element does, so there's no need to call $(this)


$(this) will wrap indeed the given object in a JQuery object -- and since selectedIndex is NOT an attribute of the html element you lose access to that property. So the right way to access that property is indeed by not wrapping this in a jquery object -- so this.selectedIndex.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜