Arthur Tarasov Arthur Tarasov - 2 months ago 5x
Javascript Question

jQuery .on Event does not work with a variable selector

I need to create on Click functionality for a dynamically loaded element. The ID of this element is in a variable

. The ID is stored a string. I pass it to the
event handler like this:

... .on("click", '"'+$element+'"', function() { ...

It doesn't work and gives out an error
Uncaught Error: Syntax error, unrecognized expression: "#2"
(see Case 1 JSFiddle).
is the ID of the element.

Then I tried wrapping it in a function like this:

... .on("click", function() {'"'+$element+'"'}, function() { ...

But it seems to turn the whole DOM into a clickable element (see Case 2 JSFiddle). Why...?

Finally, Case 3 JSFiddle shows the behavior I want: if the user clicks the element with ID
, something happens, if she clicks the element with ID
or anywhere else, nothing happens. I just can't get it to work when the selector is passed as a variable.

Case 1 JSFiddle gives out a weird error.

Case 2 JSFiddle click "a" or "b" and "a" will turn red.

Case 3 JSFiddle is what I am after. Click "a", it turns red, click "b" nothing happens.


From your fiddle, have a look at this:

var $element = '#a2';

        $element,       // <-- child Selector
        function() {
            .filter(function() {
                return $(this).text() === 'a';
            .css('background-color', 'red');

Please note that ids should not start with numbers, at least in 4 times.