如何在jQuery中默认获取第一个HTML选项的值

How to get the value of the first HTML option by default in jQuery?

本文关键字:HTML 第一个 选项 获取 默认 jQuery      更新时间:2023-09-26

我使用jQuery 1.9.1和jQuery Mobile 1.3.1,我有这样的HTML:

        <p>
            How many days did your menstrual cycle last?
            <select id="menstrualCycle" onclick="changeFunc('menstrualCycle')">
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="5">5</option>
                <option value="6">6</option>
                <option value="7">7</option>
            </select>
        </p>

然后我有一个这样的JS:

function changeFunc(select) {
    var selectBox = document.getElementById(select);
    var selectedValue = selectBox.options[selectBox.selectedIndex].value;
    if (select == 'monthCycle') {
        monthDays = selectedValue;
        console.log("Month value is: " + monthDays);
    } else if (select == 'menstrualCycle') {
        menstrualDays = selectedValue;
        console.log("Menstrual value is: " + menstrualDays);
    } else if (select == 'lutealPhase') {
        lutealValue = selectedValue;
        console.log("Luteal value is: " + lutealValue);
    }
}

关键是我通过单击选项或选择其他选项来获得值。但是当页面打开时,我的页面id是"ovulInfoPicker",默认情况下它不会获得第一个值。我想在默认情况下获得第一个值,而不改变值或按下选项。

以编程方式触发变更事件:http://api.jquery.com/trigger.

$('#id1, #id2, #id3').trigger('change');

触发事件,该事件将在没有实际用户交互的情况下执行事件处理程序。

<option value="3" selected="selected">3</option>