Jquery开关按钮

时间:2014-01-22 02:57:31

标签: jquery button

我不能为我的生活让这个按钮正常工作!基本上我希望它添加城市图层,并根据点击删除城市图层。

<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);

  }

});   

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);