如何将jQuery对象用于选择框

How to use jQuery object for a select box

本文关键字:用于 选择 对象 jQuery      更新时间:2023-09-26

我需要在下拉列表中选择一个值,并在某个位置显示。选择框是用一个变量形成的,所以我做的是

jQuery('<select>'+projAddHocs+'</select>')
    .find('[value='+val[59]+']')
    .attr('selected','selected')
    .prop('outerHTML');

jQuery('<select>'+projAddHocs+'</select>').val(val[59]).prop('outerHTML');

val[59]具有在显示之前需要在下拉列表中选择的值。

当select存在于DOM中时,这很容易,但我无法使用jQuery包装器来完成。

有什么帮助/指示吗?

谨致问候。

您之所以选择所选<option>中的outerHTML,是因为您是通过find()到达的。

使用parent():返回您的select

jQuery('<select>'+projAddHocs+'</select>')
    .find('[value='+val[59]+']')
    .attr('selected','selected')
    .parent()
    .prop('outerHTML');

查看小提琴

或者更好:

var select = jQuery('<select>'+projAddHocs+'</select>');
select.find('[value='+val[59]+']').attr('selected','selected');
$('#wrapper').html(select.prop('outerHTML'));

请参阅fiddle

尝试检索select的值:

$("#mySelect").val(); // this returns the selected value of the drop down
// (assuming your select tag has id attribute with value 'mySelect')

如果你想设置它的值,你可以试试这个:

$("#mySelect").val('myValue'); // this sets the value to 'myValue'
// If there is an '<option>' whose value is 'myValue', 
// then this option will be selected