2012-02-16 16 views
15

voglio usare jQuery per costruire HTML come questo:utilizzare jQuery per costruire un ancoraggio

<li><a href="#"><span class="play"></span><span class="trackName">Track Name</span></a></li> 

Sembra semplice, ma non riesco a capire come inserire i tag HTML come parte del mio testo di ancoraggio.

se uso qualcosa come:

$("<a />", { text: $('<SPAN class="play" />') + "Track Name" }) 

poi i tag span ottenere sfuggito.

risposta

28

Ci sono diversi modi per farlo, tra cui (ma non solo):

// one big string 
$('<a href="#"><span class="play"></span><span class="trackName">Track Name</span></a>') 

// create <a> then append() the span 
$('<a></a>').attr("href","#") 
      .append('<span class="play"></span><span class="trackName">Track Name</span>'); 

// create <a> then set all of its contents with html() 
$('<a></a>').attr("href","#") 
      .html('<span class="play"></span><span class="trackName">Track Name</span>'); 

// append spans created earlier: 
var spans = $('<span class="play"></span><span class="trackName">Track Name</span>'); 
var a = $('<a></a>').append(spans); 

noti che .html() sostituisce qualsiasi e tutti i contenuti esistenti, mentre .append() aggiunge alla fine. Quindi, dato che ci sono due elementi span nel vostro esempio si potrebbe creare quelle in modo indipendente e aggiungere uno alla volta:

$('<a href="#"></a>').append('<span class="play"></span>') 
        .append('<span class="trackName">Track Name</span>'); 
+0

L'ultimo esempio è quello con cui sono andato. – Eric

6

goccia costruttore interna jQuery:

$("<a />", { text: '<SPAN class="play" /> Track Name' }); 

jsFiddle.

o, se si desidera che il codice come HTML nel link:

$("<a />", { html: '<SPAN class="play" /> Track Name' }); 
+0

la cosa più strana è che il cursore non è più un puntatore, quindi è necessario aggiungere uno stile come su http: // jsfi ddle.net/f2dcN/41/, o avere CSS per forzare il cursore in un puntatore quando si passa il mouse sull'elemento di ancoraggio – patrick

0
//overwrites the innerHTML of all anchors *selector must be changed to more specific 
$('a').html('<span class="play"></span><span class="trackName">Track Name</span>'); 

//wraps existing text and prepends the new span 
$('a').wrapInner('<span class="trackName">') 
    .prepend('<span class="play"></span>'); 

http://jsfiddle.net/gaboesquivel/f2dcN/3/

0

Questo è ciò che alla fine andato con:

$('<a>', { className: 'trackName', href: contentPath + 'tracks/' + t.fileName }) 
    .append('<span class="play" />') 
    .append('<span class="trackName"></span>') 
      .append(t.trackName) 
2
var link = $("<a>"); 
    link.attr("href","http://www.google.com"); 
    link.attr("title","Google.com"); 
    link.text("Google"); 
    link.addClass("link"); 
Problemi correlati