Agregue el estilo OOP de elementos html usando jQuery

Is there a way instead of doing something like this:

for (item in list){
  $("#myList").append("<option>" + list[item] + "</option>");
}

To instead do something like:

for (item in list){
   var option = new option(list[item]);
   $("#myList").add(option);
}

myList being a drop down selection in the html. I know for this example it doesn't much matter, I'm just thinking if the thing that gets appended (the <option>) becomes more complicated.

Muchas Gracias

preguntado el 08 de noviembre de 11 a las 18:11

2 Respuestas

Utilizan Option y select.add (native functions):

var select = $("#myList")[0];
for(var item in list){
    var option = new Option(list[item]);
    select.add(option);
}

respondido 08 nov., 11:22

Can you point me to some documentation where I can read about the Option? - Tyler DeWitt

@TylerDeWitt See: new Option(). - Rob W

Normalmente hago algo como esto:

var $opt;
for (item in list) {
    $opt = $('<option/>').text(list[item]).appendTo('#myList');
}

It's a clear, OOP-like, jQuery-like way of doing things, with the added benefit of producing a variable storing the new HTML element as a jQuery object, for further manipulation.

respondido 08 nov., 11:22

As a add-on for this, you can actually do $('<option>', {text:"some text", "class": "some class"}) - Caramelos Gratis

Thanks for this idea. I like the syntax of the other answer a little more, but I'll definitely keep this in the toolbox as well - Tyler DeWitt

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.