使用JQuery构建锚点
我想使用jquery来构建这样的HTML:
Track Name
这看起来很简单,但我无法弄清楚如何将HTML标记作为我的锚文本的一部分。
如果我使用类似的东西:
$("", { text: $('') + "Track Name" })
然后span标签被转义。
有几种方法可以做到,包括(但不限于):
// one big string $('Track Name') // create then append() the span $('').attr("href","#") .append('Track Name'); // create then set all of its contents with html() $('').attr("href","#") .html('Track Name'); // append spans created earlier: var spans = $('Track Name'); var a = $('').append(spans);
请注意, .html()
替换任何和所有现有内容,而.append()
添加到结尾。 因此,假设您的示例中有两个span元素,您可以单独创建它们并一次附加一个:
$('').append('') .append('Track Name');
删除内部jQuery构造函数:
$("", { text: ' Track Name' });
jsFiddle 。
或者,如果您希望链接中的代码为HTML:
$("", { html: ' Track Name' });
var link = $(""); link.attr("href","http://www.google.com"); link.attr("title","Google.com"); link.text("Google"); link.addClass("link");
这就是我最终选择的内容:
$('', { className: 'trackName', href: contentPath + 'tracks/' + t.fileName } ) .append('') .append('') .append(t.trackName)
//overwrites the innerHTML of all anchors *selector must be changed to more specific $('a').html('Track Name'); //wraps existing text and prepends the new span $('a').wrapInner('') .prepend('');