【问题标题】:Jquery change selected option troublejQuery更改选择的选项麻烦
【发布时间】:2014-11-19 09:44:37
【问题描述】:

我在使用 HTML 中的 <select options> 标记时遇到问题。

我正在尝试使用 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 长轮询,因为我知道这会给我们的服务器带来压力。

【问题讨论】:

  • 有几件事情是错误的:1) 你绑定到同一个元素的 change 事件两次并反击另一个绑定正在做的事情,2) 然后你在绑定后立即触发更改更改事件,3)您正在覆盖任何选择更改的值,因此无论如何都无法从选择列表中选择除第一个选项之外的任何内容。除此之外,您可能不应该使用 jQuery 来更改 ajax 调用的值,您应该使用用户选择的任何值:$("#block_name").val() 将起作用。

标签: javascript jquery html ajax


【解决方案1】:

如果我知道你在做什么:

  • 与其获取所选optiontext,不如获取select 元素的value
  • 而不是定义更改事件处理程序(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' );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多