Javascript 如何在更改时打印下拉列表中的第一个元素?

Javascript 如何在更改时打印下拉列表中的第一个元素?,javascript,jquery,Javascript,Jquery,我有这个功能: function LoadRegions() { var region = $('#RegionID'); var url = "/Account/GetRegions"; $.getJSON(url, { countryId: $('#CountryID').val() }, function (response) { // clear and add default (null) option //region.

我有这个功能:

function LoadRegions() {
    var region = $('#RegionID');


    var url = "/Account/GetRegions";
    $.getJSON(url, { countryId: $('#CountryID').val() }, function (response) {
        // clear and add default (null) option 

        //region.empty().append($('<option></option>').val('').text('Please select'));



        for (var i = 0; i < response.length; i++) {
            region.append($('<option></option>').val(response[i].Id).text(response[i].Name));
        }

    });
}
当用户选择countrie时,我调用此函数,但我希望在开始时显示该列表中的第一个元素。。。 通过这一行,我得到请选择,但我需要列表中的第一个元素:

  region.empty().append($('<option></option>').val('').text('Please select'));

如果我对这一行进行注释,则显示为空…有帮助吗?

您需要设置选项标记中选定的属性,以便将选项设置为选定。为此,您需要修改for循环,如下所示:

for (var i = 0; i < response.length; i++) {
    if(i==0)
        region.append($('<option selected></option>').val(response[i].Id).text(response[i].Name));
    else
        region.append($('<option></option>').val(response[i].Id).text(response[i].Name));
}

我相信问题可能是链接的问题。有关详细信息,请参阅文档

在同一个链上执行了清空和追加操作。由于链式算法,这有时会导致问题。报告对这个问题有很好的描述

这可以解决你的问题

$.getJSON(url, {
    countryId: $('#CountryID').val()
}, function(response) {
    // clear and add default (null) option 
    region
        .empty()
        .end()
        .append($('<option>', {
            value: '',
            text: 'Please select'
        }));
    $.each(response, function(key, tocken) {
        region.append($('<option>', {
            value: tocken["Id"],
            text: tocken["Name"]
        }));
    });
});
$.getJSON(url, {
    countryId: $('#CountryID').val()
}, function(response) {
    // clear and add default (null) option 
    region
        .empty()
        .end()
        .append($('<option>', {
            value: '',
            text: 'Please select'
        }));
    $.each(response, function(key, tocken) {
        region.append($('<option>', {
            value: tocken["Id"],
            text: tocken["Name"]
        }));
    });
});