简体   繁体   中英

how to make id which is not a unfixed value in $(“#”) works?

My code as below:

 var tElement=document.getElementById("test"); for(i=0;i<num;i++) { var img=document.createElement('img'); img.src="img.jpg"; img.id="'r'+i"; tElement.appendChild(img); Tclick(i); } function Tclick(num){ $("'#r'+num").click(function (num) { $("#display").append("<img src='img2.jpg'>"); }); } 
 <div id="test"></div> <div id="display"></div> 

however, the application always say '#r'+num is unexpected error, I don't how to write it so that it can work. plz help me. thanks.

You are not using variable's properly. Since i and num are variable you don't need to wrap it in quotes.

Use

img.id='r'+i;

instead of

img.id="'r'+i";

And

$('#r'+num)

instead of

$("'#r'+num")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM