2014-01-22 3 views
0

Я не могу на всю жизнь заставить эту кнопку работать правильно! По сути, я хочу, чтобы он добавил слой городов и удалил слой городов на основе щелчка.Кнопка включения и выключения JQuery

<button id="mainCities" class="classname"> <span class="ui-button-text">Main Cities</span></button> 

$("#mainCities").click(function(){ 
    $("span", this).text(function(i, text){ 
    return text === "Main Cities" ? "Main Cities Off" : "Main Cities" 
    }) 

    if ($("span", this).text == "Main Cities Off"){ 
    alert('map off'); 

       map.removeLayer(mainCitiesLayer); 
    } 
    if ($("span", this).text == "Main Cities"){ 
     alert('map on'); 
     map.addLayer(mainCitiesLayer); 

    } 

}); 
+1

Не должны ** $ (» span ", this) .text ==" Main Cities Off ") ** be ** $ (" span ", this) .text() ==" Main Cities Off ") ** ?? то же самое для «on» тоже – ggdx

ответ

1

.text() является функцией не является свойством

$("#mainCities").click(function() { 
    //cache the span reference as it is used again 
    var $span = $("span", this).text(function (i, text) { 
     return text === "Main Cities" ? "Main Cities Off" : "Main Cities" 
    }) 

    //.text() is a function invoke it to get the value of text 
    if ($span.text() == "Main Cities Off") { 
     alert('map off'); 
     map.removeLayer(mainCitiesLayer); 
    //since there are only 2 states there is no need to use another if condition 
    } else { 
     alert('map on'); 
     map.addLayer(mainCitiesLayer); 
    } 
}); 

Демо: Fiddle

+0

спасибо arun! Это было именно то, что мне нужно. Я не знал об этом. Еще раз спасибо! – paintball247

1

.text является метод:

var method = $("span", this).text(function(i, currentText) { 
    return currentText === "Main Cities" 
         ? "Main Cities Off" 
         : "Main Cities"; 
}).text() === 'Main Cities' ? 'addLayer' : 'removeLayer'; 

map[method](mainCitiesLayer); 
Смежные вопросы