How to pass a variable to jQuery query?

For some reason this works:

var oldText = $("#tayke li:eq(" + theIndex + ")" ).text();

But this is not so:

var tayke_li =  "#tayke li:eq(" + theIndex + ")"
var oldTest = $( tayke_li ).text();

Note: theIndex is an integer.

+3
source share
3 answers

He works both ways. I redid it and it worked. Check the theIndex variable for changes and scope. Try replacing it with hardcoded 1

adding jQuery version information to the question, and the browser spec would be nice too.

+1
source

It doesn't matter if you put a comma at the end of the line:

var tayke_li =  "#tayke li:eq(" + theIndex + ")"; //<---

I installed a simple example and it works great:

alert($("#tab1").length);
var s = "#tab" + String(1); //alerts "1"
alert(s);  //alerts "#tab1"
alert($(s).length); //alerts 1

, theIndex String(). , tayke_li

?

JavaScript?

javascript?

JavaScript?

http://www.webmasterworld.com/forum91/521.htm

0

to try

var oldText = $("#tayke li:eq("+parseInt(theIndex)+")").text();

or

var oldText = $("#tayke li").eq(theIndex).text();
0
source

Source: https://habr.com/ru/post/1732537/


All Articles