以下代码设置为在页面上选择2个下拉值,但工作正常,但是,即使选择了第一个下拉列表,页面也会刷新,因此不会保留dropdpwn值。
如何保留下拉值?
$(document).ready(function() {
$('.boxy').hide();
var drop1Value = '';
var drop2Value = '';
var cntyS = getUrlVars()['cntry'];
var piS = getUrlVars()['PI'];
$("#drop1").on("change", function() {
var drop1Value = $('#drop1').val();
if (drop1Value == "") {
$('#content').hide();
} else {
drop1Value = $('#drop1').val();
}
var bURL = document.location.origin + document.location.pathname + '?cntry=' + drop1Value + '&PI=' + piS;
window.location.href = bURL;
});
$("#drop2").on("change", function() {
var drop2Value = $('#drop2').val();
if (drop2Value == "") {
$('#content').hide();
} else {
drop2Value = $('#drop2').val();
}
var bURL = document.location.origin + document.location.pathname + '?cntry=' + cntyS + '&PI=' + drop2Value;
window.location.href = bURL;
});
});
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
答案 0 :(得分:0)
jQuery支持方法链接。你可以利用它来设置这样的值:
$('myselector').on('...', function () {}).val(myValue)
在您的情况下,这是正确的代码:
$(document).ready(function() {
$('.boxy').hide();
var drop1Value = '';
var drop2Value = '';
var cntyS = getUrlVars()['cntry'];
var piS = getUrlVars()['PI'];
$("#drop1").on("change", function() {
var drop1Value = $('#drop1').val();
if (drop1Value == "") {
$('#content').hide();
} else {
drop1Value = $('#drop1').val();
}
var bURL = document.location.origin + document.location.pathname + '?cntry=' + drop1Value + '&PI=' + piS;
window.location.href = bURL;
}).children('[value="'+cntyS+'"]').prop('selected', true);
$("#drop2").on("change", function() {
var drop2Value = $('#drop2').val();
if (drop2Value == "") {
$('#content').hide();
} else {
drop2Value = $('#drop2').val();
}
var bURL = document.location.origin + document.location.pathname + '?cntry=' + cntyS + '&PI=' + drop2Value;
window.location.href = bURL;
}).children('[value="'+piS+'"]').prop('selected', true);
});
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}