jQuery: using a variable as a selector
This question already has an answer here:
- jQuery selectors with variables 5 answers
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.
The jQuery is as follows:
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.
I'd appreciate any guidance on what I'm doing wrong and how to correct it.
Thanks
You're thinking too complicated. It's actually just $('#'+openaddress)
.
ReferenceURL : https://stackoverflow.com/questions/17097947/jquery-using-a-variable-as-a-selector
'development' 카테고리의 다른 글
NOT DUPLICATED 값만있는 PHP 병합 배열 (0) | 2021.01.09 |
---|---|
How to get rid of the underline in a Spannable String with a Clickable Object? (0) | 2021.01.09 |
How to recover a corrupt SQLite3 database? (0) | 2021.01.09 |
MySQL : 오류 1215 (HY000) : 외래 키 제약 조건을 추가 할 수 없습니다. (0) | 2021.01.09 |
Java mapping: Selma vs MapStruct (0) | 2021.01.09 |