JQuery: using a variable as a selector

I'm having problems using a variable as a selector for the paragraph on which I want to take action. In particular, I have several title elements and the same number of paragraphs. The desired result is that if I click on Title1, I will start with step 1. I made a simple example for development purposes, in which, if I click on the title, the text of the corresponding paragraph will change color. If I program hard the solution, it works, but is passed to the variable when the selector fails.

jQuery looks like this:

jQuery(document).ready(function($){ $(this).click(function(){ var target=(event.target.id);// Get the id of the title on which we clicked. We will extract the number from this and use it to create a new id for the section we want to open. alert(target);// checking that we are getting the right value. var openaddress=target.replace(/click/gi, "section");//create the new id for the section we want to open. alert('"#'+openaddress+'"');//Confirm that the correct ID has been created $('"#'+openaddress+'"').css( "color", "green" );//get the id of the click element and set it as a variable. //$("#section1").css( "color", "green" );//Test to confirm that hard coded selector functions correctly. return false;// Suppress the action on the anchor link. }); }); 

Warning returns the following variable alert returned showing the value of the variable which seems correct and matches the hard-coded version. I omitted html since it works in a hard coded version. I believe that there are no problems on this side.

I would be grateful for what I am doing wrong, and how to fix it.

thank

+45
variables jquery jquery-selectors
Jun 13 '13 at 22:04 on
source share
1 answer

You think too hard. This is actually just $('#'+openaddress) .

+114
Jun 13 '13 at 22:05
source share



All Articles