admin管理员组文章数量:1426066
how would I add a link to each list item?
basically I have a list and i want to use js or jquery to added in href for my search page.
<aside class="listlinks">
<ul>
<li>CRM</li>
<li>CTI</li>
<li>Call Center</li>
<li>Data warehouse</li>
<li>Documentum D2</li>
<li>MDM</li>
<li>SharePoint</li>
</ul>
</aside>
$('.listlinks').each(function(){
$(this).wrapInner('<a href="\search.php?' + $(this).html() + '" />');
});
how would I add a link to each list item?
basically I have a list and i want to use js or jquery to added in href for my search page.
<aside class="listlinks">
<ul>
<li>CRM</li>
<li>CTI</li>
<li>Call Center</li>
<li>Data warehouse</li>
<li>Documentum D2</li>
<li>MDM</li>
<li>SharePoint</li>
</ul>
</aside>
$('.listlinks').each(function(){
$(this).wrapInner('<a href="\search.php?' + $(this).html() + '" />');
});
Share
Improve this question
edited Dec 18, 2015 at 18:00
Zakaria Acharki
67.5k15 gold badges78 silver badges106 bronze badges
asked Dec 18, 2015 at 17:54
Rayen KamtaRayen Kamta
2143 silver badges10 bronze badges
1
- Update: Make sure to encode the text in the url. Just remembered that.(developer.mozilla/en-US/docs/Web/JavaScript/Reference/…) – Lucas Commented Dec 18, 2015 at 18:06
4 Answers
Reset to default 3Your example would work as long as you updated the jQuery selector to match the list items instead of the parent list, e.g. replace .listlinks
with .listlinks ul li
. You should also make sure you properly encode the text in the href
portion with encodeURI
or encodeURIComponent
.
You don't really need jQuery for this and using pure Javascript and manually concatenating would save you 3-4 function calls per list item.
$('.listlinks ul li').each(function(){
this.innerHTML = '<a href="\search.php?' + encodeURIComponent(this.innerHTML) + '">' + this.innerHTML + '</a>';
});
You can shorten this even more by sacrificing one function call per list item and using String.prototype.link
. The link
method automatically wraps string objects with a hyperlink to the supplied URL.
$('.listlinks ul li').each(function(){
this.innerHTML = this.innerHTML.link('\search.php?' + encodeURIComponent(this.innerHTML));
});
$('.listlinks ul li').each(function(){
$(this).append('<a href="\search.php?' + $(this).html() + '" />');
});
You could do
$('.listlinks ul li').each(function(){
var text = $(this).html();
$(this).html('<a href="\search.php?' + encodeURIComponent(text) + '">' + text + '</a>');
});
Update: Make sure to encode the text in the url. Just remembered that
@ Rayen Kamta try this:
$.each($('.listlinks li'),function(k,v){
$(v).wrap('<a href="\search.php?' + $(v).html() + '" />');
});
本文标签: javascriptJS OR Jquery to Add Link to List itemsStack Overflow
版权声明:本文标题:javascript - JS OR Jquery to Add Link to List items - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745417289a2657743.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论