How do I create a string and use the function named after it?

Sorry for the bad wording in the question, but it's hard for me to explain. I am using a few bxsliders in the page and some in hidden divs. Unfortunately the images are not shown in the slider after the parent div is shown unless the slider is reloaded (see here: bxSlider inside show / hide divs ). So, let's say I start the sliders at the beginning:

var slider_0=$("#slider_0 .bxslider").bxSlider({
    //bxslider options here

var slider_4=$("#slider_4 .bxslider").bxSlider({
    //bxslider options here

var slider_7=$("#slider_7 .bxslider").bxSlider({
    //bxslider options here


The sliders will not be numbered sequentially, but there is navigation and if I click on the 7th item it will result in slider_7. So I could get the index of the clicked item with:



When I call slider_7.reloadSlider();

it will work, but I don't know which slider the user is clicking and what number it has. So one would call it with the generated string like this:



works of course. Is there a way to do this?


source to share

6 answers

Found a working solution:

eval("slider_" + $(this).index()).reloadSlider();




I would create a dictionary with strings as keys and functions as values. Then you can have an O (1) search for the functions you are targeting.

In general, you can do it like this:

// set up your dictionary
var dictionary = {};

// add your functions
dictionary['methodName'] = function() {};

// call the functions


So, for your example, you can do:

dictionary['slider_7'] = slider_7.reloadSlider;





You can call it with

window["slider_" + $(this).index()].reloadSlider()


Although, I'm not sure if your approach is the best. I think I would go with arrays or with an object (as key-value pairs)



Try the following:

$("#" + slider_name + " .bx_slider").reloadSlider();




It is not entirely clear what you want / are trying to do. What you seem to want to do is get a programmatic handle on a specific slider when the user clicks on a specific part of your page. You are not doing this with a eval()

string ... for which event handlers. So create a click event handler and a click event handler

$('#idOfWhatTheUserClicksOn').click(function(event) {
    var slider = document.getElementById('#idOfRelatedSlider');
    //if you need the current value of the slider you can get that too
    var value = slider.value;


You can achieve the same thing with less LOCs by using a class instead of id with different handlers, but the concept is the same.



var slider_cache = [
    $("#slider_0 .bxslider").bxSlider(),
    $("#slider_1 .bxslider").bxSlider(),
    $("#slider_2 .bxslider").bxSlider()







All Articles