2014-01-22 65 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()==”主要城市关闭“)** ??相同的“上”一个 – 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

谢谢阿伦!那正是我需要的。我没有意识到有关文字。再次谢谢你! – 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);