我有四个清单
<li class='lists'>http://google.com</li>
<li class='lists'>http://facebook.com</li>
<li class='lists'>http://twitter.com</li>
<li class='lists'>http://youtube.com</li>
我想在列表的值中包含一个a
标记,其中href=
值来自列表中的值。
我想要达到的最终结果是:
<li class='lists'><a href="http://google.com">http://google.com</a></li>
<li class='lists'><a href="http://facebook.com">http://facebook.com</a></li>
<li class='lists'><a href="http://twitter.com">http://twitter.com</a></li>
<li class='lists'><a href="http://youtube.com">http://youtube.com</a></li>
到目前为止,我使用jQuery
$('li.lists').wrapInner('<a class="links"> </a>');
使用li
标记将a
内的内容包装起来,但我对如何将链接放入a
字段的逻辑缺乏了解。
我试过
$.each($('.links'), function() {
$('.links').attr({'href':$(this).text()});
})
但是这会更改指向http://youtube.com
的所有链接,这是最后一个链接,您可以在JSFiddle here
答案 0 :(得分:4)
您可以继续使用wrapInner。只需使用以下语法:
$('li.lists').wrapInner(function () {
return "<a href='" + $(this).text() + "'></a>";
});
<强> jsFiddle example 强>
答案 1 :(得分:1)
你接近你的最后一个例子。试试这个:
$('.lists').each(function() {
var href = $(this).text();
$(this).html($('<a>').attr('href', href).text(href));
});
答案 2 :(得分:1)
尝试
$('li.lists').html(function (_, old_html) {
return '<a href="' + old_html + '">' + old_html + '</a>';
});
<小时/>
.html()
答案 3 :(得分:1)
如this jQuery article所述,$ .each用于非JQuery对象,而.each()用于jQuery对象。由于您使用jQuery选择器设置每个标记的href属性,因此您需要使用.each()以这种方式使用wrapInner及其href设置标记:
$('.lists').each(function() {
$(this).wrapInner('<a class="links"> </a>');
$(this).children('a').attr({'href':$(this).text()});
})
<强> jsfiddle example 强>
答案 4 :(得分:0)
你应该尝试这样的事情:
$('.lists').each(function() {
$(this).wrapInner('<a class="links" href="'+$(this).text()+'"> </a>');
});
答案 5 :(得分:0)
您还可以使用$.each为所有li.list
和$.append()添加子元素(<a>
标记)。
<强>演示强>
$('li.lists').each((i,el) => {
let text =$(el).text();
$(el).text('');
$(el).append($('<a>').attr('href', text).text(text));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class='lists'>http://google.com</li>
<li class='lists'>http://facebook.com</li>
<li class='lists'>http://twitter.com</li>
<li class='lists'>http://youtube.com</li>