Pregunta

El ejemplo que veo publicado todo el tiempo parece subóptimo, porque implica concatenar cadenas, lo que parece no ser jQuery.Suele tener este aspecto:

$.getJSON("/Admin/GetFolderList/", function(result) {
    for (var i = 0; i < result.length; i++) {
        options += '<option value="' + result[i].ImageFolderID + '">' + result[i].Name + '</option>';
    }
});

¿Existe una mejor manera?

¿Fue útil?

Solución

Andreas Grech estaba bastante cerca ... en realidad es this (tenga en cuenta la referencia a <=> en lugar del elemento en el bucle):

var $dropdown = $("#dropdown");
$.each(result, function() {
    $dropdown.append($("<option />").val(this.ImageFolderID).text(this.Name));
});

Otros consejos

$.getJSON("/Admin/GetFolderList/", function(result) {
    var options = $("#options");
    //don't forget error handling!
    $.each(result, function(item) {
        options.append($("<option />").val(item.ImageFolderID).text(item.Name));
    });
});

Lo que estoy haciendo arriba es crear un nuevo <option> elemento y agregándolo al options lista (asumiendo options es el ID de un elemento desplegable.

PD: Mi javascript está un poco oxidado, por lo que es posible que la sintaxis no sea perfecta.

Claro - haz options una serie de cadenas y uso .join('') en vez de += cada vez a través del bucle.Ligera mejora en el rendimiento cuando se trata de una gran cantidad de opciones...

var options = [];
$.getJSON("/Admin/GetFolderList/", function(result) {
    for (var i = 0; i < result.length; i++) {
        options.push('<option value="',
          result[i].ImageFolderID, '">',
          result[i].Name, '</option>');
    }
    $("#theSelect").html(options.join(''));
});

Sí.Sigo trabajando con cuerdas todo el tiempo.Lo creas o no, esa es la forma más rápida de construir un fragmento DOM...Ahora bien, si sólo tienes unas pocas opciones, realmente no importará: utiliza la técnica Dreams demuestra si te gusta el estilo.Pero tenga en cuenta que está invocando el analizador HTML interno del navegador. i*2 veces, en lugar de solo una vez, y modificando el DOM cada vez a través del bucle...con un número suficiente de opciones.Terminarás pagando por ello, especialmente en navegadores más antiguos.

Nota: Como señala Justice, esto se desmoronará si ImageFolderID y Name no son codificado correctamente...

O tal vez:

var options = $("#options");
$.each(data, function() {
    options.append(new Option(this.text, this.value));
});

La forma más rápida es esta:

 $.getJSON("/Admin/GetFolderList/", function(result) {
        var optionsValues = '<select>';
        $.each(result, function(item) {
            optionsValues += '<option value="' + item.ImageFolderID + '">' + item.Name + '</option>';
        });
        optionsValues += '</select>';
        var options = $('#options');
        options.replaceWith(optionsValues);
    });

Según este enlace es la forma más rápida porque envuelve todo en un solo elemento al hacer cualquier tipo de inserción DOM.

Encontré que esto funcionaba desde el sitio jquery

$.getJSON( "/Admin/GetFolderList/", function( data ) {
  var options = $("#dropdownID");
  $.each( data, function(key, val) {
    options.append(new Option(key, val));
  });
});

Lo he leído usando fragmentos de documentos es eficaz porque evita el reflujo de página en cada inserción de elemento DOM, también es compatible con todos los navegadores (incluso IE 6).

var fragment = document.createDocumentFragment();

$.each(result, function() {
  fragment.appendChild($("<option />").val(this.ImageFolderID).text(this.Name)[0]);
});

$("#options").append(fragment);

Leí por primera vez acerca de esto en Curso de prácticas recomendadas de JavaScript de CodeSchool .

Aquí hay una comparación de diferentes enfoques , gracias al autor .

Otro enfoque con ES6

fetch('https://restcountries.eu/rest/v1/all')
  .then((response) => {
    return response.json()
  })
  .then((countries) => {
    var options = document.getElementById('someSelect');
    countries.forEach((country) => {
      options.appendChild(new Option(country.name, country.name));
    });
  })

Uso el selectboxes jquery plugin. Convierte tu ejemplo en:

$('#idofselect').ajaxAddOption('/Admin/GetFolderList/', {}, false);
$.get(str, function(data){ 
            var sary=data.split('|');
            document.getElementById("select1").options.length = 0;
            document.getElementById("select1").options[0] = new Option('Select a State');
            for(i=0;i<sary.length-1;i++){
                document.getElementById("select1").options[i+1] = new Option(sary[i]);
                document.getElementById("select1").options[i+1].value = sary[i];
            }
            });
function generateYears() {
                    $.ajax({
                        type: "GET",
                        url: "getYears.do",
                        data: "",
                        dataType: "json",
                        contentType: "application/json",
                        success: function(msg) {
                            populateYearsToSelectBox(msg);
                        }
                    });
}

function populateYearsToSelectBox(msg) {
  var options = $("#selectYear");
$.each(msg.dataCollecton, function(val, text) {
   options.append(
        $('<option></option>').val(text).html(text)
    );
});
}

Espero que ayude. Usualmente uso funciones en lugar de escribir todo el código cada vez.

    $("#action_selector").change(function () {

        ajaxObj = $.ajax({
            url: 'YourURL',
            type: 'POST', // You can use GET
            data: 'parameter1=value1',
            dataType: "json",
            context: this,                
            success: function (data) {
                json: data              
            },
            error: function (request) {
                $(".return-json").html("Some error!");
            }
        });

        json_obj = $.parseJSON(ajaxObj.responseText);            

        var options = $("#selector");
        options.empty();
        options.append(new Option("-- Select --", 0));
        $.each(ajx_obj, function () {
            options.append(new Option(this.text, this.value));
        });
    });
});

He estado usando jQuery y llamé a una función para completar menús desplegables.

function loadDropDowns(name,value)
{
   var ddl = "#Categories";
   $(ddl).append('<option value="' + value + '">' + name + "</option>'");
}
function LoadCategories() {
    var data = [];
    var url = '@Url.Action("GetCategories", "InternalTables")';
    $.getJSON(url, null, function (data) {
        data = $.map(data, function (item, a) {
            return "<option value=" + item.Value + ">" + item.Description + "</option>";
        });
        $("#ddlCategory").html('<option value="0">Select</option>');
        $("#ddlCategory").append(data.join(""));
    });
}

aquí hay un ejemplo que hice al cambiar obtengo hijos de la primera selección en la segunda selección

jQuery(document).ready(function($) {
$('.your_select').change(function() {
    $.ajaxSetup({
        headers:{'X-CSRF-TOKEN': $("meta[name='csrf-token']").attr('content')}
    });

    $.ajax({
        type:'POST',
        url: 'Link',
        data:{
          'id': $(this).val()
        },
        success:function(r){
          $.each(r, function(res) {
                console.log(r[res].Nom);
                 $('.select_to_populate').append($("<option />").val(r[res].id).text(r[res].Nom));
            });
        },error:function(r) {
          alert('Error');
        }
    });
});

});enter code here

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top