Create a link from text
I have code
<div class="row1">
<em>My text</em>
</div>
How can I make a link like:
<div class="row1">
<em><a href="/mylink">My text</a>开发者_高级运维;</em>
</div>
I understand that the issue is a primitive but can not find the same simple solution.
You can use contents() with wrapAll():
$(".row1 em").contents().wrapAll("<a href='/mylink'></a>");
$('.row1 em').html(function(i, contents) {
return '<a href="/mylink">' + contents + '</a>';
});
or
$('.row1 em').contents().wrapAll('<a href="/mylink" />');
you can try this-
$(".row1 em").contents().wrapAll("<a href='/mylink'></a>")
$('.row1 em').html().wrap('<a href="/mylink">');
If your aim is to hyperlink the text, and you can afford alternate solutions, following achieves the same:
HTML:
<div class="row1">
<em>My text</em>
</div>
CSS:
.row1 {
cursor:pointer;
}
JS:
$('.em').click(function() {
location.href = '/mylink';
});
Example:
$('.row1 em').wrap('<a href="/mylink" />');
Update: Since this will wrap the <a>
tags around <em>
instead its contents, the correct way is to use $('.row1 em').contents().wrap('<a href="/mylink" />');
as Frederic stated
精彩评论