Esiste un equivalente jQuery del costruttore Element () di MooTools?
-
05-07-2019 - |
Domanda
Ho intenzione di avviare un motore di report javascript per il mio sito Web e ho avviato alcuni prototipi utilizzando MooTools. Mi piace molto poter fare cose del genere:
function showLeagues(leagues) {
var leagueList = $("leagues");
leagueList.empty();
for(var i = 0; i<leagues.length; ++i) {
var listItem = getLeagueListElement(leagues[i]);
leagueList.adopt(listItem);
}
}
function getLeagueListElement(league) {
var listItem = new Element('li');
var newElement = new Element('a', {
'html': league.name,
'href': '?league='+league.key,
'events': {
'click': function() { showLeague(league); return false; }
}
});
listItem.adopt(newElement);
return listItem;
}
Da quello che ho visto, " di jQuery; adotta " i metodi di tipo accettano solo stringhe HTML o elementi DOM. Esiste un jQuery equivalente a Element di MooTools?
EDIT: La cosa grande che sto cercando qui è l'allegato programmatico del mio evento click al link.
Soluzione
sintatticamente, potrebbe essere più bello usare jQuery per farlo, ma è probabilmente più efficiente da usare
document.createElement('li')
Ed elimina la necessità di eseguire almeno un test di confronto delle stringhe e un'analisi dei token minori.
flydom può anche solleticare il tuo interesse se insisti nel generare molti nodi dom. (Dovrebbe essere più veloce in teoria, ma non l'ho testato)
Nota: internamente, jQuery (" < html > < / html > ") sembra che lo faccia effettivamente ( troppo semplificata):
jQuery(matcher) --> function(matcher)
{
return jQuery.fn.init(matcher) --> function(matcher)
{
return this.setArray(
jQuery.makeArray(
jQuery.clean(matcher) --> function(matcher)
{
div = document.createElement('div');
div.innerHTML = matcher;
return div.childNodes;
}
)
);
}
}
Quindi si presume " document.createElement
" è quindi un " requisito " ;, e se sai ciò che desideri (ovvero: non paragonare alcuni dati di terze parti con $( datahere )
), allora jQuery(document.createElement('div'))
verrebbe essere altrettanto logico e con un aumento di velocità per evitare le numerose regexps e le manipolazioni lente delle stringhe.
In confronto: <=> sembra che lo faccia effettivamente (semplificato eccessivamente):
jQuery(matcher) --> function(matcher)
{
return jQuery.fn.init(matcher) --> function(matcher)
{
this[0] = matcher;
this.length = 1;
return this;
}
}
Altri suggerimenti
Ecco la stessa cosa in jQuery. Fondamentalmente per creare un nuovo elemento, devi solo inserire l'HTML che desideri.
function showLeagues(leagues) {
var $leagueList = $("#leagues");
$leagueList.empty();
$.each(leagues, function (index, league) {
$leagueList.append(getLeagueListElement(league));
});
}
function getLeagueListElement(league) {
return $('<li></li>')
.append($('<a></a>')
.html(league.name)
.attr('href', '?league=' + league.key)
.click(function() {
showLeague(league);
return false;
})
)
;
}