Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery打开和关闭按钮_Jquery_Button - Fatal编程技术网

Jquery打开和关闭按钮

Jquery打开和关闭按钮,jquery,button,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){

我这辈子都不能让这个按钮正常工作!基本上,我希望它添加城市层,并根据单击删除城市层

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

  }

});   
主要城市
$(“#主要城市”)。单击(函数(){
$(“span”,this).text(函数(i,text){
返回文本==“主要城市”?“主要城市关闭”:“主要城市”
})
if($(“span”,this).text==“主要城市关闭”){
警报(“地图关闭”);
地图移除层(mainCitiesLayer);
}
if($(“span”,this).text==“主要城市”){
警报(“地图开启”);
map.addLayer(mainCitiesLayer);
}
});   
.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);
    }
});

演示:

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

$(“span”,this).text==“主要城市关闭”)不应该是$(“span”,this.text()==“主要城市关闭”)吗??同样的,你这个阿伦!这正是我所需要的。我没有意识到这是关于文本的。再次感谢你!