jquery:下拉菜单中var的if语句

jquery:下拉菜单中var的if语句,jquery,drop-down-menu,if-statement,var,Jquery,Drop Down Menu,If Statement,Var,我为下拉菜单应用了替换,而jQuery替换保持为空,因为选择选项表单的预选值未定义(值是动态生成的)。当我单击替换并选择一个选项时,它会正常工作。以下是替换代码的摘录,我认为这是错误的原因: function createDropDownSF(){ var searchForm_type = $("#searchForm_type"); var selected = searchForm_type.find("option[selected]"); var options = $("

我为下拉菜单应用了替换,而jQuery替换保持为空,因为选择选项表单的预选值未定义(值是动态生成的)。当我单击替换并选择一个选项时,它会正常工作。以下是替换代码的摘录,我认为这是错误的原因:

function createDropDownSF(){
  var searchForm_type = $("#searchForm_type");
  var selected = searchForm_type.find("option[selected]");
  var options = $("option", searchForm_type);
因此,我尝试使用此代码扩展函数,以使函数在没有选定值时使用第一个选项,但它不起作用:

if (selected.is("undefined")) {
    searchForm_type.find("option")[0];
}

有人有想法吗?

我会先尝试从所有选择的选项中获取一个列表,并检查长度是否>0

 $("select option:selected").length > 0
然后可以使用JQuery选择第一个选项

$('select option').first().attr('selected', true);

你是那个意思吗

function createDropDownSF(){
  var searchForm_type = $("#searchForm_type");
  var selected = searchForm_type.find("option[selected]");
        $("select option:selected").length > 0;
        $('select option').first().attr('selected', true);
  var options = $("option", searchForm_type);

我不知道如何设置没有选择值的select,但是这段代码应该可以工作

searchForm_type.find(“选项”)[0]这只是找到第一个选项,它对它没有任何作用。你是否使用某种插件来替换下拉列表?是的,这是我在网上找到的替换插件。上面的代码被添加到插件中,作为预选值问题的解决方法。但正如您所描述的,我应该添加一行来使用find选项来显示?
<select id="test">
<option>1</option>
<option>2</option>
<option selected="selected">3</option>
<option>4</option>
$(function () {

    if ($("#test option:selected").length > 0) {
        // something is selected
        alert("selected");
    } else {
        // nothing is selected
        $('#test option').first().attr('selected', true);
    }
});