我在 <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/