创建一个切换按钮,在图层打开和图层关闭时改变文本

Create a toggle button that changes text when layer is on and when layers is off

本文关键字:图层 文本 改变 一个 按钮 创建      更新时间:2023-09-26

我已经创建了这个代码,它创建了一个切换按钮,可以在传单中打开和关闭图层。打开和关闭图层很好。但我还希望切换按钮中的文本能够改变。当一个图层在传单地图上时,它必须说:"图层",当地图上没有图层时,它需要说:"图层关闭"。我试着实现

$(this).text(function(i, text){
    return text == 'Layer off';
});

$(this).text(function(i, text){
     return text == 'Layer on';
});

但是它在按钮中返回文本"false"。下面是我使用的函数:

$("#layerControl").click(function(event) {
  layerClicked = window[event.target.value];
  if (map.hasLayer(layerClicked)) {
    map.removeLayer(layerClicked);
    $(this).text(function(i, text) {
      return text == 'Layer off';
    });
  } else {
    map.addLayer(layerClicked);
    $(this).text(function(i, text) {
      return text == 'Layer on';
    });
  }
});

编辑

我正试图在选择列表中进行更改后再次启动该函数。这是我现在的代码,但它还没有工作:

$('#slctListValue').change(function ()
{
        $("#layerControl").click(function( event ) {
                    layerClicked = window[event.target.value];
                        if (map.hasLayer(layerClicked)) {
                            map.removeLayer(layerClicked);
                            $(this).text('Layer Off');
                        }
                        else{
                            map.addLayer(layerClicked);
                            $(this).text('Layer On');
                        } ;
        });
});

我建议根据当前文本内容有条件地返回字符串值,而不是返回布尔值。

下面,我使用一个三元操作符来确定新的文本。

$('button').on('click', function() {
  $('#output').text(function(i, text) {
    return text == 'Layer off' ? 'Layer on' : 'Layer off';
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button">CLICK ME</button>
<div id="output">Layer off</div>


编辑:

然而,看看你的代码的精神和意图,我可能只是根据图层是否显示设置适当的文本。两个单独的条件可能会使事情复杂化,并引入意想不到的行为。

$("#layerControl").click(function(event) {
  layerClicked = window[event.target.value];
  if (map.hasLayer(layerClicked)) {
    map.removeLayer(layerClicked);
    $(this).text('Layer Off');
  } else {
    map.addLayer(layerClicked);
    $(this).text('Layer On');
  }
});

试试这个

text == 'Layer off'; // not-work!    
text = 'Layer off'; // work!