繁体   English   中英

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

[英]jquery: if-statement for var in dropdown-menu

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

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 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);
    }
});

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

暂无
暂无

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

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