最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin8浏览0评论

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]);
发布评论

评论列表(0)

  1. 暂无评论