繁体   English   中英

如何立即更新 jquery 中的选择器下拉值?

[英]How can I instantly update my selector dropdown value in jquery?

我写了以下代码;

var region = $('#inputGroupSelect01').val()
region = $('#inputGroupSelect01').change(function() {
  $(this).val()
})
console.log(region)

控制台显示k.fn.init(1) 但我希望$(this).val()将更新区域变量的值。 如何在更改事件中将$(this).val()设置为区域?

编辑 1

我想要危险部分中的这个region变量。 像这样;

var hazardLayer = L.tileLayer.wms("http://localhost:8080/geoserver/tajikistan/wms", {
    layers: `tajikistan:${region}`,
    format: 'image/png',
    transparent: true,
    version: '1.1.0',
    attribution: "country layer"
  });

我也想要全局hazardLayer中的 hazardLayer。 我不能把它放在change事件中。

编辑 2

hazardLayer会像这样在点击function中使用;

$('#load').click(function () {
  hazardLayer.addTo(map);
});

$('#clear').click(function () {
  map.removeLayer(hazardLayer);
})

我有 10 多个层,例如hazardLayer和 7 个变量,例如region 我需要干净的代码,所以我希望两者都在全局 scope 中。

就像您说的那样,您可以将区域变量定义为全局上下文,并通过定义基于传递层返回层的 function 来减少代码行/复杂性。


var region
var currentLayer

var region = $('#inputGroupSelect01').val()
region = $('#inputGroupSelect01').change(function () {
    $(this).val()
});

function createLayer(region) {
    return L.tileLayer.wms("http://localhost:8080/geoserver/tajikistan/wms", {
        layers: `tajikistan:${region}`,
        format: 'image/png',
        transparent: true,
        version: '1.1.0',
        attribution: "country layer"
    });
}

$('#load').click(function () {
    currentLayer = createLayer(region)
    currentLayer.addTo(map);
});

$('#clear').click(function () {
    map.removeLayer(currentLayer);
});

我知道答案已经在评论中给出,但要显示答案的有效证据。

看看下面的代码,正如@user2932057 在问题的评论部分所说,

区域将在全球范围内可用,

要检查region值是否更新,您只需单击按钮即可查看region的结果值

 var region = $('#inputGroupSelect01').val(); var options = { layers: `tajikistan:${region}`, format: 'image/png', transparent: true, version: '1.1.0', attribution: "country layer" }; var hazardLayer = L.tileLayer.wms("http://localhost:8080/geoserver/tajikistan/wms", options); $('#inputGroupSelect01').change(function() { region = $(this).val(); options.layers = `tajikistan:${region}`; console.log(region); }); console.log(region); $('#load').click(function () { hazardLayer = L.tileLayer.wms("http://localhost:8080/geoserver/tajikistan/wms", options); hazardLayer.addTo(map); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="inputGroupSelect01"> <option value="option1">option1</option> <option value="option2">option2</option> <option value="option3">option3</option> <option value="option4">option4</option> </select> <button id="load">Click Me</button>

您不需要为它保留全局变量。 只需在需要时获得价值。

console.log(getRegion())

function getRegion() {
    return $('#inputGroupSelect01').val()
}
$('#inputGroupSelect01').on('change',function(){
   var region =  $(this).val();
   console.log(region);
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM