1

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.

Arthur Tarasov
  • 3,517
  • 9
  • 45
  • 57
  • 1
    you output `'"#2"'` as a string, which is invalid. additionally, ids should not start with numbers. just write: `.on("click", $element, function() { ...` since `$element` already is a string – Alex Aug 15 '16 at 12:47
  • https://jsfiddle.net/p4ursy9r/5/ – Alex Aug 15 '16 at 12:50
  • @Alex https://www.w3.org/TR/html5/dom.html#the-id-attribute They can – epascarello Aug 15 '16 at 12:53

1 Answers1

1

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.

Community
  • 1
  • 1
Alex
  • 9,911
  • 5
  • 33
  • 52
  • ids can start with numbers. https://www.w3.org/TR/html5/dom.html#the-id-attribute – epascarello Aug 15 '16 at 12:53
  • @epascarello i didnt say anything different :) i updated the answer though – Alex Aug 15 '16 at 12:53
  • I am laughing with a facepalm. Apparently just putting `$element` there works. IDs in my real code start with letters, I just simplified them in the example. I think I should leave the IDs in my question as is here so the answer carries an additional bit of information. – Arthur Tarasov Aug 15 '16 at 12:59
  • sure, there needs to be a string, so any variable of type string can be put there :) writing `'#2'` is the same as `$element`, when it is a string variable with that exact value :) – Alex Aug 15 '16 at 13:01