我创建了这个代码,它制作了一个切换按钮,可以在传单中打开和关闭图层。打开和关闭图层效果很好。但我还希望更改切换按钮中的文本。当传单 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/