Use JQuery to build an anchor

青春壹個敷衍的年華 提交于 2019-11-28 07:02:55

问题


I want to use jquery to build HTML like this:

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

It seems simple but I can't figure it out how to include HTML tags as part of my anchor text.

If I use something like:

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

then the span tags get escaped.


回答1:


There are several ways to do it, including (but not limited to):

// 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);

Note that .html() replaces any and all existing contents, while .append() adds to the end. So given that you have two span elements in your example you could create those independently and append them one at a time:

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



回答2:


Drop the internal jQuery constructor:

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

jsFiddle.

or, if you want the code as HTML in the link:

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



回答3:


var link = $("<a>");
    link.attr("href","http://www.google.com");
    link.attr("title","Google.com");
    link.text("Google");
    link.addClass("link");



回答4:


This is what I eventually went with:

$('<a>', { className: 'trackName', href: contentPath + 'tracks/' + t.fileName } )
     .append('<span class="play" />')
     .append('<span class="trackName"></span>')
          .append(t.trackName)



回答5:


//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/



来源:https://stackoverflow.com/questions/9304342/use-jquery-to-build-an-anchor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!