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

标签 javascript jquery leaflet layer togglebutton

我创建了这个代码,它制作了一个切换按钮,可以在传单中打开和关闭图层。打开和关闭图层效果很好。但我还希望更改切换按钮中的文本。当传单 map 上有图层时,它必须说:“图层打开”,而本地图上没有图层时,它需要说:“图层关闭”。我尝试实现

$(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');
                        } ;

        });
});

最佳答案

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

下面,我使用 ternary operator确定新文本。

$('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');
  }
});

关于javascript - 创建一个切换按钮,在图层打开和关闭时更改文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38085522/

相关文章:

javascript - VanillaJS Promise 实现替换 jQuery 通知/进度事件

javascript - ondrop 事件 - 创建新元素

leaflet - Leaflet 中是否有类似于 Google map 中的 isLocationOnEdge() 的内容?

java - 如何从 JSP 获取图像 blob 到 JavaScript?

javascript - 如何在重复的div中添加索引? (javascript)

javascript - 为什么jQuery或诸如getElementById之类的DOM方法找不到元素?

javascript - 当我在生产模式下将源代码与 webpack 捆绑时,如何避免丢失类名?

javascript - jQuery 验证插件 : redirect user if any particular condition is invalidated

javascript - 通过 leaflet.js 中的单击事件自动删除以前的标记并在 map 上添加新标记

javascript - 传单鼠标悬停弹出数组列表