1

我为下拉菜单应用了替换,并且 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];
}

有人有想法吗?

4

3 回答 3

0

你是那个意思吗?

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);
于 2012-12-04T08:54:03.720 回答
0
<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);
    }
});

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

于 2012-12-06T12:12:06.913 回答
0

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

 $("select option:selected").length > 0

然后您可以使用 JQuery 选择第一个选项。

$('select option').first().attr('selected', true);
于 2012-12-04T08:16:26.857 回答