Particularly the bit about live....
jQuery('.something').live('click', function() {
jQuery(this).parent('form').reset();
});
I suppose this might work as well, thoug开发者_开发技巧h I am curious about the parent function:
jQuery('.something').live('click', function() {
this.form.reset();
});
Live
Prototype doesn't currently have "live" support. You can do something similar with event delegation, though. That's where you watch for the event on a parent element, and then in the event handler find out which child element the event actually happened on:
$('theFormID').observe('click', handleFormClick);
function handleFormClick(event) {
var element;
// Get the element on which the click occurred
element = event.findElement();
}
Event delegation is only possible with events that bubble (like 'click'); I don't know if jQuery's live stuff has that same issue.
One nice thing is that you can pass CSS selectors into Event#findElement
:
$('tbodyID').observe('click', handleTableClick);
function handleTableClick(event) {
var element;
// Get the element on which the click occurred
element = event.findElement('tr');
}
...which finds the tr
that was clicked, even if the actual click occurred within a span
inside a td
inside the tr
.
Proper use of event delegation can dramatically simplify hooking/unhooking elements, particular when you're adding and removing elements dynamically.
I wouldn't be surprised if there's a plug-in for Prototype that does "live" support.
Parent
You mentioned that you want to get the parent of the clicked control. When you hook up a handler with Prototype, by default it sets things up so that within your handler, this
references the element on which you've set the event handler. So for instance, if you have a div
with the id foo
:
$('foo').observe('click', function(event) {
// Here, `this` will refer to the `foo` element
});
You can then use Prototype's Element#up to get the parent element. (If you're using event delegation and you hook the event on the parent in the first place, of course just use this
directly and if you also need to get a reference to the thing that was clicked, use #findElement
as above.)
精彩评论