简体   繁体   English

如何获得dom修改选择框的当前选择选项?

[英]How to get the currently selected option of a dom modified select box?

I'm using a fake select box in my script which means the original select box is hidden and for styling purposes a ul is showing up. 我在脚本中使用了伪造的选择框,这意味着原始选择框已隐藏,并且出于样式目的,正在显示ul。 Whenever the selected value of this list changes the orginal select box does too. 每当此列表的选定值更改时,原始选择框也将更改。

There is a change function for that. 有一个更改功能。 Within that function is following code: 该函数中包含以下代码:

var el = $(e.currentTarget) ;
$('#my_select_box').children().removeAttr('selected');
$('#my_select_box  option[value="'+el.attr('data-value')+'"]').attr('selected','selected');

After that change I want to retrieve the new selected value of the original select box in another function. 更改之后,我想在另一个函数中检索原始选择框的新选择值。

But the normal selector only gets the original value, not the new: 但是普通选择器仅获取原始值,而不获取新值:

$('#my_select_box option:selected').val() //returns the wrong value

So how to I get the new value in the function I need it? 那么,如何在需要的函数中获取新值呢?

I tried this function: 我试过这个功能:

$("#my_select_box").bind("DOMSubtreeModified", function() {
    console.log($(this).find('option:selected').val());    
});

It returns the correct value but not where I need it. 它返回正确的值,但不在我需要的地方。 So how can I retrieve the correct select box value out of the domtree live? 那么如何从domtree live中检索正确的选择框值?

Thanks in advance! 提前致谢!

instead of .attr('selected','selected'); 而不是.attr('selected','selected'); , try .prop('selected', true); ,尝试.prop('selected',true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM