[英]How to add anchor tag to text inside a list
I have this list 我有这个清单
<ul>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
</ul>
I wanted to wrap all the Text inside the list with anchor tag for example something like this 我想用锚标签将列表中的所有文本包装起来,例如这样的东西
<ul>
<li><a href="">Test</a></li>
<li><a href="">Test</a></li>
<li><a href="">Test</a></li>
<li><a href="">Test</a></li>
</ul>
Using jquery. 使用jQuery。 The content is created dynamically so i dont have any control over the code to edit.
内容是动态创建的,因此我无法控制要编辑的代码。
I used this code from some tutorial but no success. 我使用了一些教程中的代码,但没有成功。
$("ul li").wrap(function() {
var link = $('<a/>');
link.attr('href', '');
link.text($(this).text());
return link;
});
$('ul li').contents().wrap('<a href="#"></a>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> </ul>
Simply Use .wrap()
in jquery 只需在jquery中使用
.wrap()
$('ul li').contents().wrap('<a />');
if you want add href attribute in the anchor tag 如果要在锚标记中添加href属性
$('ul li').contents().wrap('<a href="#"></a>');
(function($) {
$(function() {
$('ul li').each(function() {
var li = $(this),
text = li.text();
// li.html('<a href="">' + text + '</a>');
li.text('').append('<a href="">' + text + '</a>');
});
});
})(jQuery);
li.html('<a href="">' + text + '</a>');
would pretty much remove everything in each li
, since I dont know if that doesnt matter or not it's safer to remove the text and append an <a>
using li.text('').append('<a href="">' + text + '</a>');
将几乎在每个去除一切
li
,因为我不知道这并不重要或没有它的安全删除文本和追加的<a>
使用li.text('').append('<a href="">' + text + '</a>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.