2015-03-26 10 views
10

Questo è quello che ti dà select2.github.io:Select2 aggiungere icona immagine di opzione in modo dinamico

function addIcons(opt) { 
    if (!opt.id) { 
     return opt.text; 
    } 
    var $opt = $(
      '<span><img src="/images/flags/' + opt.element.value.toLowerCase() + '.png" class="img-flag" /> ' + opt.text + '</span>' 
      ); 
    return $opt; 
} 

vorrei aggiungere un attributo data-immagine per le mie opzioni:

<option value="flag" data-image="/images/flags/flag.png">Country 1</option> 

e loggarlo nella funzione:

function addIcons(opt) { 
    if (!opt.id) { 
     return opt.text; 
    } 

    var optimage = opt.attr('data-image'); 
    var $opt = $(
      '<span><img src="/images/flags/' + optimage + '" class="img-flag" /> ' + opt.text + '</span>' 
      ); 
    return $opt; 
} 

Purtroppo, un semplice console.log (opt); non restituisce nulla nella funzione, quindi non riesco a vedere se riesco ad accedere al mio attributo di immagine di dati. Il blocco di codice sopra riportato restituisce un errore, quindi questo ovviamente non funziona. Qualche suggerimento su questo argomento?

+0

Un errore? Qual è il messaggio di errore specifico? Hai una demo di jsfiddle? – PeterKA

risposta

8

Se OptImage restituisce "indefinito" provare il mio campione: il suo bel lavoro:

$("#selectUserForChat").select2({ 
 
\t \t templateResult: addUserPic, 
 
     templateSelection: addUserPic 
 
}); 
 
\t 
 
function addUserPic (opt) { 
 
\t if (!opt.id) { 
 
\t \t return opt.text; 
 
\t }    
 
\t var optimage = $(opt.element).data('image'); 
 
\t if(!optimage){ 
 
\t \t return opt.text; 
 
\t } else { 
 
\t \t var $opt = $(
 
\t \t '<span class="userName"><img src="' + optimage + '" class="userPic" /> ' + $(opt.element).text() + '</span>' 
 
\t \t); 
 
\t \t return $opt; 
 
\t } 
 
};

3

Prova questo:

var optimage = $(opt).data('image'); //or $(opt).attr('data-image') 
var $opt = $(
    '<span><img src="' + optimage + '" class="img-flag" /> ' + $(opt).text() + '</span>' 
); 
+0

restituzioni ottimali "indefinite". L'ho provato anche in questo modo. –

5

ho risolto problema con questo codice: var optimage = $(opt.element).data('image');

$(".category").select2({ 
      templateResult: formatState, 
      templateSelection: formatState 
     }); 
     function formatState (opt) { 
      if (!opt.id) { 
       return opt.text; 
      }    
      var optimage = $(opt.element).data('image'); 
      if(!optimage){ 
       return opt.text; 
      } else {      
       var $opt = $(
        '<span><img src="' + optimage + '" width="23px" /> ' + opt.text + '</span>' 
       ); 
       return $opt; 
      } 

     }; 
+0

È lo stesso del mio esempio e non ha funzionato: var optimage = opt.attr ('data-image'); –

+0

Provo a completare la risposta –

Problemi correlati