开发者

How to pass a reference of DOM object to jQuery function?

I want to pass a reference of the开发者_开发知识库 DOM object to a jQuery function. However the function does not get a reference to the DOM object. It does get a string containing the DOM object. So i get an error on the following example

<input type="text" size="30" onchange="change_total_price(this)" id="priceField">

.

function change_total_price(input) {
    input.closest('div').find('#amountField').val());
}


You need to wrap it, like this:

function change_total_price(input) {
  var val = $(input).closest('div').find('#amountField').val();
}

this, being input in the function is a DOM element, but .closest() is a jQuery object method so you need to wrap it in $() to get a jQuery object if you want to use it.

Alternatively do this outside of your markup, like this:

$(function() {
  $("#priceField").change(function() {
    var val = $(this).closest('div').find('#amountField').val();
  });
});

This way binds the change event handler to the id="preiceField" element, you can remove the in-line onchange="change_total_price(this)"...it's both cleaner and easier to maintain (can be outside your page in an external .js loaded and cached once, for example).

As an aside, IDs should be unique, so it doesn't need to be relative at all, both of the above examples can just be:

var val = $('#amountField').val();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜