javascript - jQuery - Concatenate string with integer to create pre-existing variable - Stack Overflow

So let's say that I have a variable, slide1.var slide1 = $('#slide1');How can I concaten

So let's say that I have a variable, slide1.

var slide1 = $('#slide1');

How can I concatenate a string, such as 'slide,' with an integer to make it equal to and behave just like that above variable, slide1?

showThis('slide' + 1);

Here is my fiddle, so you can see a shortened version of my issue/confusion in action. As you'll see, the result of the concatenation is not hiding as I would expect.

Am I attempting to do something pletely taboo?

Thanks in advance!

So let's say that I have a variable, slide1.

var slide1 = $('#slide1');

How can I concatenate a string, such as 'slide,' with an integer to make it equal to and behave just like that above variable, slide1?

showThis('slide' + 1);

Here is my fiddle, so you can see a shortened version of my issue/confusion in action. As you'll see, the result of the concatenation is not hiding as I would expect.

Am I attempting to do something pletely taboo?

Thanks in advance!

Share Improve this question asked Mar 29, 2016 at 18:14 skysky 31 silver badge4 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4
var slide1 = $('#slide1');
var button = $('#button');

button.click(function() {
  showThis('slide' + 1);
});

function showThis(thisSlide) {
  alert(thisSlide);
  $("#" + thisSlide).hide();
}

Your showThis() function requires a Jquery object and what you are providing is a string. So your code should actually be this

showThis($('#slide' + 1));

you need to index into the global window object if you really want to do it this way.

var slide1 = $('#slide1');
var button = $('#button');

button.click(function() {
  showThis(window['slide' + 1]);
});

function showThis(thisSlide) {
  alert(thisSlide);
  $(thisSlide).hide();
}

however i would go with an array like the other posters have responded with

You can access properties of an object with strings, but not really variables. Like, you have an object

var slide = {
  slide1: $('#slide1'),
  var button = $('#button'),
}

You could access slide1 with a string like this

showThis(slide['slide'+1]);

The way you are trying isn't a valid way to access variables.

Any reason you can't use an array? eg:

var slides = [];
slides[0] = $('#slide0');
slides[1] = $('#slide1');
//etc
showThis(slides[1]);

or even:

var slides = [];
for(var i = 0; i< 10; i++){
    slides[i] = $('#slide' + i);
}
showThis(slides[1]);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744217021a4563601.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信