jQuery的:使用variables作为select器

我在使用一个variables作为我想要采取行动的段落的select器时遇到了问题。 具体来说,我有几个标题元素和相同数量的段落。 期望的结果是,如果我点击Title1然后我对段落1采取行动。 为了发展的目的,我做了一个简单的例子,如果我点击一个标题,那么相应段落的文本就会改变颜色。 如果我硬编码的解决scheme,它的工作原理,但在select器失败时传入一个variables。

jQuery如下:

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. }); }); 

该警报返回以下variables 警报返回显示变量的值 这似乎是正确的,并匹配硬编码的版本。 我已经省略了HTML,因为它在硬编码版本中工作,我认为这方面没有问题。

我会很感激任何指导我做错了什么,如何纠正。

谢谢

你在想太复杂 实际上只是$('#'+openaddress)