Arthur Tarasov Arthur Tarasov - 3 months ago 16
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

$element
. The ID is stored a string. I pass it to the
.on
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).
#2
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
#2
, something happens, if she clicks the element with ID
#3
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.

Answer

From your fiddle, have a look at this:

var $element = '#a2';

$("#a1").on(
        "click",
        $element,       // <-- child Selector
        function() {
            $("#a1")
            .find('span')
            .filter(function() {
                return $(this).text() === 'a';
            })
            .css('background-color', 'red');
        }
    );

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