Is it possible to add multiple selectors to delegate functions in jquery?

Something like creating a namespace / submodule for my scripts relative to the module in my application? For example, I just want to delegate certain tasks to elements inside some div, for example say # submodule1.

Can I do something like this:

$("#submodule1") .delegate(".selector1", "click", function() {} ) .delegate(".selector2", "click", function() {} ) 

And if possible, it will be the same as:

  $("#submodule1").delegate(".selector1", "click", function() {} ) $("#submodule1").delegate(".selector2", "click", function() {} ) 

EDIT

based on TJ Crowder's answer: I have to do this:

 $("#soap-test-test-cases") .delegate(".soap-test-case", "click", function(){ testfunction(); }); .delegate("legend", "click", function() { alert("this is a test!"); }); 

but I get a syntax error

+4
source share
1 answer

Edit

Your change changes the question, now you have a syntax error:

 $("#soap-test-test-cases") .delegate(".soap-test-case", "click", function(){ testfunction(); }); // v--- here .delegate("legend", "click", function() { alert("this is a test!"); }); 

If you remove the semicolon in front of it, you are fine:

 $("#soap-test-test-cases") .delegate(".soap-test-case", "click", function(){ testfunction(); }) // <== No semi here, we're not done with the statement yet .delegate("legend", "click", function() { alert("this is a test!"); }); // <== Now we're done with the statement 

This one statement spreads over several lines, which is great. You call $() and then call delegate on the object returned by $() , then calling delegate on the object that returns your first delegate call.

With a semicolon after the first delegate call, you have two statements, and the second starts with . (which is a syntax error).

JavaScript basically doesn't care about line breaks, it cares about statements that end with a semicolon. This one has horror, which is an automatic semicolon, but it will not insert semicolons that invalidate your code. (It will insert semicolons that make your code work erroneously, but, again, know where your statements start and end, and make sure that you provide the correct semicolons.)


Original answer :

The code samples that you specified are valid, and they have the same effect: combining two separate functions for processing clicks, one of them on one subset of elements ( .selector1 ), and the other on the other ( .selector2 ). Your first example is just a standard chain.

I don't think this is what you are asking for, but just in case: if you want to use the same function for both classes of elements, you can do this too:

 $("#submodule1").delegate(".selector1, .selector2", "click", function() { }); 

... or (of course) use the same function with two separate delegate calls.

+15
source

All Articles