3

Using a single dynamic selector I have no problems:

var answer_id = <?php echo $answer_id; ?>;

$('#a_flag_' + answer_id).click(function(e) {
        e.preventDefault();

         //Ajax etc...

But if I add several dynamic selectors they do not work (ie, no errors on Firebug console, but also no action when clicked):

var answer_id = <?php echo $answer_id; ?>;

$('#a_flag_' + answer_id,'#a_comments_link_' + answer_id,'#a_best_answer_' + answer_id).click(function(e) {
        e.preventDefault();

         //Ajax etc...

Any ideas what I am doing wrong?

3 Answers 3

5

You need the commas inside the quoted constant strings.

$('#a_flag_' + answer_id + ', #a_comments_link_' + answer_id + ',  #a_best_answer_' + answer_id).click(// ///

What you want to end up with is a string that looks like

"selector, selector, selector, ..."

so you need to concatenate a bunch of strings with commas.

Alternatively, you could build up your separate selectors in an array of strings and then ".join()" them with a comma separator (the parameter to ".join()").

Sign up to request clarification or add additional context in comments.

Comments

1

You should put the coma inside the string not outside and you have forgotten the plus.

$('#a_flag_' + answer_id + ', #a_comments_link_' + answer_id +',#a_best_answer_' + answer_id)

Comments

1

When it starts to look too complicated, it likely is. FWIW:

var selectors = [
  '#a_flag_' + answer_id,
  '#a_comments_link_' + answer_id
  // etc.
]
$(selectors.join(", ")).click(...)

Happy coding.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.