In JQuery, how do I add an onload or init even to an object?
I'd like to have a select box control display / hiding of sections in a form
First, I added an .change event on the item, and this works if I actually change the item
$('#mySelect').change(
function() {
开发者_开发知识库 updateSections($(this));
});
Then all I wanted is to have the .change
event be called at least once, when the page is loaded
The only way I could think of is in $(document).ready
which seems like a detached location
$(document).ready(function(){
updateSections($('#mySelect'));
}
The main issue is that I don't have the ID of the item from where I write the function (generated code)
So I would like to do something like this (conceptional code), and don't know if there is any way to do it
$('#mySelect').change(
function() {
updateSections($(this));
}).init(
function() {
updateSections($(this));
});
.load()
only works on a
/ img
tags
Also from a design perspective, the onDraw of an item is a standard event in any UI framework, and having one event directly on the object, and one on the document looks weird to me
jQuery will allow you to just call the .change()
method on load. You might do something like this:
$(document).ready(function() {
$('#mySelect').change(function() {
updateSections($(this));
});
$('#mySelect').change();
});
You can probably put .change()
after the first $('#mySelect')
occurrence for brevity, but I wanted to be verbose; the $('#mySelect').change();
will fire the defined .change()
event on the select box.
I would make UpdateSections a jQuery plugin. Follow this simple tutorial, or google for a more in depth one.
http://blog.jeremymartin.name/2008/02/building-your-first-jquery-plugin-that.html
Then you'd end up with something like this. You can act directly on the object.
$('#mySelect').change(function(){
$(this).updateSelections();
}).updateSelections();
精彩评论