jQuery:使用变量作为选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17097947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: using a variable as a selector
提问by dorich
I'm having problems using a variable as the selector for a paragraph on which I want to take action. Specifically I have several title elements and the same number of paragraphs. The desired result is that if I click on Title1 then I take an action on paragraph1. I made a simple case for development purposes whereby if I click on a title then the text of the corresponding paragraph changes color. If I hard code the solution it works but passing in a variable as the selector fails.
我在使用变量作为要对其采取行动的段落的选择器时遇到问题。具体来说,我有几个标题元素和相同数量的段落。想要的结果是,如果我点击 Title1,那么我就对 Paragraph1 采取行动。我为开发目的做了一个简单的案例,如果我点击一个标题,那么相应段落的文本会改变颜色。如果我对解决方案进行硬编码,它会起作用,但会在选择器失败时传入一个变量。
The jQuery is as follows:
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.
});
});
The alert returns the following variable
which appears to be correct and matches the hard coded version.
I've omitted the html since it works in the hard coded version I assume there is no problem on that side.
警报返回以下变量,该变量
似乎正确并与硬编码版本匹配。我省略了 html,因为它在硬编码版本中工作,我认为那一侧没有问题。
I'd appreciate any guidance on what I'm doing wrong and how to correct it.
我很感激任何关于我做错了什么以及如何纠正它的指导。
Thanks
谢谢
回答by Jan Krüger
You're thinking too complicated. It's actually just $('#'+openaddress)
.
你想的太复杂了。其实只是$('#'+openaddress)
.