Reputation: 3801
If I have a selector like $add, I can do this:
$add.click(function () {.....
But I can't do this:
$('body').delegate($add, 'click', function () {.....
How can I make it work?
Update
Taking @T.J. Crowder's answer in mind. This is the complete case, I create two buttons (which I insert to the dom)
$add = $(document.createElement('button')).addClass('add').appendTo('body');
$subtract = $(document.createElement('button')).addClass('subtract').appendTo('body');
Doing delegate on $add.selector will take effect on both those buttons, why is that?
Upvotes: 1
Views: 2046
Reputation: 1074266
You can use the selector
property. See the caveats in the docs, though, and also the notes about combining it with context
. One of those caveats (not immediately obvious from the docs, though, in my view) is that when you start modifying the selection with method calls, the selector
property becomes less useful. For instance:
var $add = $("div").not(".bar");
display("$add.length = " + $add.length);
// displays 3 in my example, because I have three divs that don't have class "bar"
display("$add.selector = " + $add.selector);
// displays "div.not(.bar)" (note the '.' rather than ':')
$add = $($add.selector);
display("$add.length = " + $add.length);
// displays 0 in my exmaple, because "not" is taken for a class name
To my mind, that makes it not very useful.
That answers the question you actually asked, but there's probably a better way to solve the underlying design problem. :-)
Update: Re your update, the problem is probably that using selector
on $add
returns "button". (I haven't tried it, it just seems likely.)
I'd solve it like this:
Option A:
If you only ever have one button with the class "add", then:
$add = $(document.createElement('button')).addClass('add').appendTo('body');
$subtract = $(document.createElement('button')).addClass('subtract').appendTo('body');
$('body')
.delegate("button.add", "click", handleAdd)
.delegate("button.subtract", "click", handleSubtract);
Option B:
If there are other buttons with those classes, give these buttons some identifying characteristic — their own class, or an id
, or a name
, then use that in the delegate
selectors. Example (but adjust as necessary):
$add = $("<button id='btnAdd' class='add'>").appendTo('body');
$subtract = $("<button id='btnSubtract' class='subtract'>").appendTo('body');
$('body')
.delegate("#btnAdd", "click", handleAdd)
.delegate("#btnSubtract", "click", handleSubtract);
Note there that I switched to HTML notation for creating the buttons, as it's more concise when you get into multiple attributes and such.
Side note: If there's a more precise container that isn't affected by the ajax update you can use, I would. Using body
as the container is pretty global. You said the form is being replaced via ajax, so whatever container you're updating in your ajax all would probably be a good choice.
Upvotes: 4