我有选择的选项和我们的价值
<select name="d11" id="d">
<option hidden> Next 3 months</option>
<option value ="3"> Next 3 months</option>
<option value ="6"> Next 6 Month</option>
<option value = "12">Next 12 Month</option>
</select>在jquery的帮助下,我能够显示在选中的输入框上更改文本,就像用户单击下一个月时所需要的那样,然后是,它应该显示(9月-12月),并且所有都是按单击。
问题:
但问题是,这个值在加载窗口时会发生变化,并显示文本(接下来的3个月),但是如果没有加载窗口,我希望九月十二月和它的工作正常。
这是剧本
$("#d").change(function() {
var $this = $( this );
if (this.value == "3") {
$this.find( "option:first" ).text( '' + "{{ Date('M
Y',strtotime("0 month"))}} - {{ Date('M Y',strtotime("+3
month"))}}" ).val("3").prop( 'selected', true )
}
else if(this.value == "6")
{
$this.find( "option:first" ).text( '' + "{{ Date('M
Y',strtotime("0 month"))}} - {{ Date('M Y',strtotime("+6
month"))}}" ).val("6").prop( 'selected', true )
}
else{
$this.find( "option:first" ).text( '' + "{{ Date('M
Y',strtotime("0 month"))}} - {{ Date('M Y',strtotime("+12
month"))}}" ).val("12").prop( 'selected', true )
}
} )
window.onload = function() {
var selItem = sessionStorage.getItem("6");
$('#d ').val(selItem);
}
$('#d').change(function() {
var selVal = $(this).val();
sessionStorage.setItem("6", selVal);
});有人能帮忙吗?
发布于 2018-09-15 08:11:33
如果我理解正确的话,通过UI选择一个值是在做您想做的事情,但是将其设置为存储值的onload代码却没有做到。
这是因为在这种情况下没有触发“更改”事件。
尝试:
window.onload = function() {
var selItem = sessionStorage.getItem("6");
$('#d').val(selItem).trigger('change');
}发布于 2018-09-15 08:48:35
您可以使用下面的代码行
$(document).ready(function () {
$("#d").change(function () {
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
var $this = $(this);
var $first = $this.find('option:eq(0)');
var nextMonth = new Date().getMonth() + 1;
var currentMonth = new Date().getMonth();
if (currentMonth == 11) {
nextMonth = 0;
}
var requiredMonth = ""
var text = "";
if (this.value == "3" || this.value == "6") {
if (this.value == "3") {
requiredMonth = currentMonth + 3;
}
else {
requiredMonth = currentMonth + 6;
}
if (requiredMonth > 11) {
requiredMonth = requiredMonth - 12;
}
text = months[nextMonth] + "-" + months[requiredMonth];
}
else {
text = months[nextMonth] + "-" + months[currentMonth];
}
$first.removeAttr('hidden');
$first.html(text);
$first.prop('selected', true);
})
});
window.onload = function () {
$('#d').trigger('change');
}
<select name="d11" id="d">
<option hidden>Next 3 months</option>
<option value="3">Next 3 months</option>
<option value="6">Next 6 Month</option>
<option value="12">Next 12 Month</option>
</select>https://stackoverflow.com/questions/52342858
复制相似问题