javascript - Jquery更改选定选项麻烦

标签 javascript jquery html ajax

我在 <select options> 方面遇到问题HTML 中的标签。

我正在尝试使用 jQuery 和 Javascript 更改选择下拉列表的值,以便我可以使用下拉列表的选定值在 AJAX 调用中执行某些操作。但是,更改后,然后我想恢复到更改之前选择的旧值,就会出现问题...我仍然可以从下拉选项中选择/选择值,但显示的值<select option>按钮/表单框是我放置在那里的最后一个值。

有办法解决这个问题吗?下面是我的代码。

//retrieving value of the selected option
var selBlock = $("#block_name option:selected").text();

//changing the value of the selected option from the dropdown to the very first option
$("#block_name").change(function() {
    $("#block_name option:first").attr('selected','selected');  
}).change();

//changing back the value of the selected option on the dropdown by reverting to the old value saved in selBlock

$("#block_name").change(function(){
    $("#block_name").find('option:selected').removeAttr("selected");
    document.getElementById('block_name').value = selBlock;
}).change();

这是我通过简单地更改下拉列表中选择的选项来实现实时效果的一种方法,因为更改它将调用 AJAX 调用并从数据库中检索新值。我选择不使用 SSE 或 AJAX 长轮询,因为我知道这会给我们的服务器带来压力。

最佳答案

如果我知道你在做什么:

  • 而不是获取 text所选的option ,前往value select的元素
  • 不定义更改事件处理程序 (2) 更改值,然后 trigger该事件

代码应如下所示:

//Save your DOM search so you don't have to repeat it
var sel = $("#block_name");

//retrieve value of the selected option
var selBlock = sel.val();

//change the value of the selected option from the dropdown to the very first option 
//& trigger change
sel.find('option:first').prop('selected', true).end().trigger( 'change' );

//change back the value of the selected option on the dropdown by reverting to
// the old value saved in selBlock & trigger change event
sel.val( selBlock ).trigger( 'change' );

关于javascript - Jquery更改选定选项麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27007286/

相关文章:

javascript - 自定义 ES6 JavaScript 错误问题

jQuery - 文本只切换一次

jquery - 使用 jQuery 动画 div

php & javascript 打开窗口函数

javascript - 使用js编辑一个PasteBin然后读取它

javascript - 未捕获的类型错误 : Cannot read property 'length' of undefined in line chart with json data

javascript - 用掩码更改类名? (查询)

javascript - jquery 表单点击时不会将值发布到 php

JQuery 无法单击 Firefox 中的自动完成下拉菜单

php - PHP Table 下的背景图——方法