It seems like there should be a better way to code this:
HTML snippet:
<label onclick="addstuff(this)" id="label_id">Hello</label>
JS/jQuery snippet:
function addstuff(field){
$('#'+field.id).before('<div>Just a random element being added…</div>');
}
I dislike that I am referencing my field in the Javascript by $(‘#’+field.id) when the field is already being passed in. It seems like there should be another way to reference field in jQuery using the field object that is passed in, which in my mind should be more efficient, but I’m not having any luck figuring it out. Any advice is greatly appreciated.
This is an easier way.
thisrefers to the label in theeventhandler function. You can also use the passed in event object in this instance. Theeventobject is implicitly passed to the function as the argument to the first parameterYou could also use an anonymous function inline
but if you want to use the function in more than one location, I would stick to the named function. It also helps when you’re debugging, as you get the name of the function when you step through.
You must bind the event handler to the element after it has been loaded into the DOM. Do this by either putting your code at the bottom of the page after the markup, or by using
$(document).ready(function() { /* code here */ });