将字符串转换为变量

时间:2016-08-12 21:53:53

标签: javascript arrays dry

我在地图对象中声明了变量,每个变量代表一个位置。然后我使用一个监听器在一个click事件上运行一个函数,所以它显示一些HTML并删除前面显示的。工作正常,但我可以看到,很快就会开始重复,而不是干涸的方法。

要显示的HTML如下:

<div class="grow-details">
    <h2>Informacion del Growshop</h2>

    <div id="imperioSeedsRecoleta" class="hide">
        <h3>Imperio Seeds</h3>
        <h5>Calle Dardignac #527</h5>

        <p>Sector Patronato</p>
        <p>Recoleta</p> 
        <p>Metro: Estacion Patronato</p>
        <p>Contacto: 56 9 73507638 (Whatsapp)</p>
        <p>Lunes a Viernes: 10:00 a 19:00 (Horario Continuado)</p>
        <p>Sabados              : 10:00 a 16:00 hrs</p>
        <p>Encargado tienda: Vicente Ogaz</p>
    </div>

    <div id="somaGrowshop" class="hide">
        <h3>Soma Growshop</h3>

        <p>José Miguel de La Barra 454, Santiago de Chile</p>
        <p>Lun-Dom: 10:00-22:00</p>
        <p>Cafetería Sensorial</p>
        <p>No requiere reservas, Para llevar y Mesas en el exterior</p>
        <p>Sirve Café y Bebidas</p>
        <p>Teléfono (2) 2639 0442</p>
    </div>

    <div id="growGames" class="hide">
        <h3>Grow Games | Grow Shop Chile</h3>

        <p>GrowGames es un GrowShop, centrados en el trato directo con nuestros clientes, resolviendo cualquier duda que pueda surgirles, dando la solución mas económica y rápida posible.</p>
        <p>Local 65,Merced 832,Santiago,Región Metropolitana</p>
        <p>+56 9 8 158 00 45 | +56 2 2 696 82 97</p>
        <p>info@growgames.cl</p>
    </div>

    <div id="dinafem" class="hide">
        <h3>Dinafem Store Santiago</h3> 
        <p>Av. Libertador Bernardo Ohiggins #482 8330030 Santiago Chile | Ecuador #78 Viña del Mar Chile</p>
        <p>Llámanos ahora: Tienda Alameda: +569 64208716 Tienda en linea: +569 965061168</p>
        <p>Escríbanos un Email a: compras@dinafemstore.cl</p>
    </div>
</div> 

这是JS文件,变量表示地图中的位置,下面是侦听器。

var dinafem = new google.maps.Marker({
    position: {lat: -33.4420634, lng: -70.64286479999998},
    map: map,
    title: 'Dinafem'
});
var growGames = new google.maps.Marker({
    position: {lat: -33.4384068, lng: -70.64886280000002},
    map: map,
    // icon: 'assets/logo.png',
    title: 'Grow Games'
});
var imperioSeedsRecoleta = new google.maps.Marker({
    position: {lat: -33.4319006, lng: -70.64667589999999},
    map: map,
    // icon: 'assets/logo.png',
    title: 'Imperio Seeds'
});
var somaGrowShop = new google.maps.Marker({
    position: {lat: -33.4371948, lng: -70.6435702},
    map: map,
    title: 'Soma Grow Shop',
    draggable: true,
    animation: google.maps.Animation.DROP
});

我的目的是遍历HTML中的每个id名称以提取id名称将其转换为变量,以便我可以调用de adsListener方法。

imperioSeedsRecoleta.addListener("click", function() {
  document.getElementById("imperioSeedsRecoleta").removeAttribute("class", "hide");

    for (i = 0; i < document.getElementsByClassName("grow-details")[0].children.length; i++) {        
        document.getElementsByClassName("grow-details")[0].children[i].setAttribute("class", "hide");       
        if (document.getElementsByClassName("grow-details")[0].children[i].id == "imperioSeedsRecoleta") {
            document.getElementById("imperioSeedsRecoleta").removeAttribute("class", "hide");
        }
    }
});

somaGrowShop.addListener("click", function() {
    document.getElementById("somaGrowshop").removeAttribute("class", "hide");

    for (i = 0; i < document.getElementsByClassName("grow-details")[0].children.length; i++) {        
        document.getElementsByClassName("grow-details")[0].children[i].setAttribute("class", "hide");       
        if (document.getElementsByClassName("grow-details")[0].children[i].id == "somaGrowshop") {
            document.getElementById("somaGrowshop").removeAttribute("class", "hide");
        }
    }
});

growGames.addListener("click", function() {
    document.getElementById("growGames").removeAttribute("class", "hide");

    for (i = 0; i < document.getElementsByClassName("grow-details")[0].children.length; i++) {        
        document.getElementsByClassName("grow-details")[0].children[i].setAttribute("class", "hide");       
        if (document.getElementsByClassName("grow-details")[0].children[i].id == "growGames") {
            document.getElementById("growGames").removeAttribute("class", "hide");
        }
    }
});

dinafem.addListener("click", function() {
    document.getElementById("dinafem").removeAttribute("class", "hide");

    for (i = 0; i < document.getElementsByClassName("grow-details")[0].children.length; i++) {        
        document.getElementsByClassName("grow-details")[0].children[i].setAttribute("class", "hide");       
        if (document.getElementsByClassName("grow-details")[0].children[i].id == "dinafem") {
            document.getElementById("dinafem").removeAttribute("class", "hide");
        }
    }
});

如果我创建一个空数组,我可以循环遍历每个div id并推送每个id名称,我方便地将其命名为与其位置变量相同

var growsArray = [];

for (i = 0; i < document.getElementsByClassName("grow-details")[0].children.length; i++) { 
    if (document.getElementsByClassName("grow-details")[0].children[i].id !== "") {       
        growsArray.push(document.getElementsByClassName("grow-details")[0].children[i].id);
    }
}

每个名称都以字符串形式返回,因此我无法调用.addlistener方法。有没有办法将这个字符串转换为变量?

3 个答案:

答案 0 :(得分:0)

创建变量时,将它们放入对象中,然后可以按名称引用它们。

例如

var dinafem = new google.maps.Marker({
    position: {lat: -33.4420634, lng: -70.64286479999998},
    map: map,
    title: 'Dinafem'
});

会变成:

var variables = {};
variables.dinafem = new google.maps.Marker({
    position: {lat: -33.4420634, lng: -70.64286479999998},
    map: map,
    title: 'Dinafem'
});

variables.growGames = //...
variables.imperioSeedsRecoleta = //...

然后您可以使用以下字符串名称全部引用它们:

variables['dinafem']; //this is the marker

因此假设您的growArray中包含字符串列表,您将遍历该列表并使用每个值从&#34;变量&#34;中获取标记。对象:

for (var i = 0; i < growsArray.length; i++) {
    var stringName = growsArray[i];
    variables[stringName].addListener(...);
}

答案 1 :(得分:0)

使用名称填充growsArray后,您可以通过window[...]访问全局变量,并添加如下事件监听器:

for (var id of growsArray) {
    window[id].addEventListener('click', function() { ... } );
}

答案 2 :(得分:0)

将变量转换为对象键,稍微抽象一下事件处理程序并迭代对象键(请注意,我已删除了代码中的一些有问题的部分(removeAttribute('class', 'hide')应该是classList.remove('hide')并通过在变量中存储元素来减少DOM查询的数量:

var locations = {
    'dinafem': new google.maps.Marker(...),
    'growGames': new google.maps.Marker(...),
    'imperioSeedsRecoleta': new google.maps.Marker(...),
    'somaGrowShop': new google.maps.Marker(...)
}

var clickHandler = function(selector) {
    return function (event) {
        var elem = document.getElementById(selector);
        var growDetails = document.querySelector("grow-details");

        elem.classList.remove("hide");

        for (i = 0; i < growDetails.children.length; i++) {        
            growDetails.children[i].classList.add("hide");       
            if (growDetails.children[i].id == selector) {
                elem.classList.remove("hide");
            }
        }
    }
}

Object.keys(locations).forEach(function(location) {
    locations[location].addListener('click', clickHandler(location));
});
相关问题