2013-06-08 20 views
28

Voglio creare una funzione per aggiungere alcuni elementi in modo programmatico su una pagina. Diciamo che voglio aggiungere un elenco a discesa con quattro opzioni:Javascript - aggiungi seleziona a livello di programmazione

<select name="drop1" id="Select1"> 
    <option value="volvo">Volvo</option> 
    <option value="saab">Saab</option> 
    <option value="mercedes">Mercedes</option> 
    <option value="audi">Audi</option> 
</select> 

Come posso farlo?

+1

sguardo nel 'document.createElement' e' element.appendChild' – Ian

+0

@koukouloforos è la mia risposta è stata utile? – WooCaSh

+2

@WooCaSh fa quello che sto chiedendo ma preferisco se qualcosa in semplice javascript. –

risposta

96

Ciò funzionerà (puro JS, aggiungendo ad un div di id myDiv):

var myDiv = document.getElementById("myDiv"); 

//Create array of options to be added 
var array = ["Volvo","Saab","Mercades","Audi"]; 

//Create and append select list 
var selectList = document.createElement("select"); 
selectList.id = "mySelect"; 
myDiv.appendChild(selectList); 

//Create and append the options 
for (var i = 0; i < array.length; i++) { 
    var option = document.createElement("option"); 
    option.value = array[i]; 
    option.text = array[i]; 
    selectList.appendChild(option); 
} 

Demo: http://jsfiddle.net/4pwvg/

+5

+1, tra le quattro opzioni solo una è javascritpt ..quanto è popolare la jquery ... – pinkpanther

+8

È un miracolo! Una soluzione non jQuery. Potresti semplicemente voler impostare le proprietà, invece degli attributi con 'setAttribute()'. E non che sia importante, ma usare 'new Option (text, value)' è una bella scorciatoia per creare '

+0

Grazie! Questo è esattamente quello che stavo cercando. –

6
var sel = document.createElement('select'); 
sel.name = 'drop1'; 
sel.id = 'Select1'; 

var cars = [ 
    "volvo", 
    "saab", 
    "mercedes", 
    "audi" 
]; 

var options_str = ""; 

cars.forEach(function(car) { 
    options_str += '<option value="' + car + '">' + car + '</option>'; 
}); 

sel.innerHTML = options_str; 


window.onload = function() { 
    document.body.appendChild(sel); 
}; 
+0

Questa è la soluzione più veloce e funziona con set di dati di grandi dimensioni. –

+0

@RomanNewaza, controlla la velocità con il ciclo forE sostituito da un normale ciclo for. – 7stud

2

ho rapidamente fatto una funzione che può raggiungere questo obiettivo, si può non è il modo migliore per farlo ma funziona semplicemente e dovrebbe essere cross browser, per favore sappi anche che NON sono un esperto in JavaScript quindi qualsiasi consiglio è fantastico :)

Pure Javascript Crea Elemento Soluzione

function createElement(){ 
    var element = document.createElement(arguments[0]), 
     text  = arguments[1], 
     attr  = arguments[2], 
     append = arguments[3], 
     appendTo = arguments[4]; 

    for(var key = 0; key < Object.keys(attr).length ; key++){ 
     var name = Object.keys(attr)[key], 
      value = attr[name], 
      tempAttr = document.createAttribute(name); 
      tempAttr.value = value; 
     element.setAttributeNode(tempAttr) 
    } 

    if(append){ 
     for(var _key = 0; _key < append.length; _key++) { 
      element.appendChild(append[_key]); 
     } 
    } 

    if(text) element.appendChild(document.createTextNode(text)); 

    if(appendTo){ 
     var target = appendTo === 'body' ? document.body : document.getElementById(appendTo); 
     target.appendChild(element) 
    }  

    return element; 
} 

Vediamo come facciamo questo

<select name="drop1" id="Select1"> 
    <option value="volvo">Volvo</option> 
    <option value="saab">Saab</option> 
    <option value="mercedes">Mercedes</option> 
    <option value="audi">Audi</option> 
</select> 

qui Funziona così

var options = [ 
     createElement('option', 'Volvo', {value: 'volvo'}), 
     createElement('option', 'Saab', {value: 'saab'}), 
     createElement('option', 'Mercedes', {value: 'mercedes'}), 
     createElement('option', 'Audi', {value: 'audi'}) 
    ]; 


    createElement('select', null, // 'select' = name of element to create, null = no text to insert 
     {id: 'Select1', name: 'drop1'}, // Attributes to attach 
     [options[0], options[1], options[2], options[3]], // append all 4 elements 
     'body' // append final element to body - this also takes a element by id without the # 
    ); 

questo è il params

createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element'); 

Questa funzione sarebbe adatto se devi ap molti elementi, se c'è un modo per migliorare questa risposta per favore fatemelo sapere.

edit:

Ecco una demo di lavoro

JSFiddle Demo

Questo può essere altamente personalizzato per soddisfare il vostro progetto!

1

Questo codice creerebbe dinamicamente un elenco di selezione. Per prima cosa creo un array con i nomi delle auto. Secondo, creo dinamicamente un elemento select e lo assegno ad una variabile "sEle" e lo aggiungo al corpo del documento html. Quindi io uso un ciclo for per fare un ciclo attraverso l'array. In terzo luogo, creo dinamicamente l'elemento opzione e lo assegno a una variabile "oEle". Usando un'istruzione if, assegno gli attributi 'disabled' e 'selected' al primo elemento opzione [0] in modo che sia selezionato sempre e sia disabilitato. Creo quindi un array di nodi di testo "oTxt" per aggiungere i nomi degli array e quindi aggiungere il nodo di testo all'elemento opzione che viene successivamente aggiunto all'elemento select.

var array = ['Select Car', 'Volvo', 'Saab', 'Mervedes', 'Audi']; 
 

 
var sEle = document.createElement('select'); 
 
document.getElementsByTagName('body')[0].appendChild(sEle); 
 

 
for (var i = 0; i < array.length; ++i) { 
 
    var oEle = document.createElement('option'); 
 

 
    if (i == 0) { 
 
    oEle.setAttribute('disabled', 'disabled'); 
 
    oEle.setAttribute('selected', 'selected'); 
 
    } // end of if loop 
 

 
    var oTxt = document.createTextNode(array[i]); 
 
    oEle.appendChild(oTxt); 
 

 
    document.getElementsByTagName('select')[0].appendChild(oEle); 
 
} // end of for loop

+0

Aggiungi spiegazione pertinente per il tuo codice. – Sandeep

Problemi correlati