将锚附加到包含具有相同href属性的锚的父级 [英] append anchor to a parent that contains anchor with same href attribute
问题描述
我是SO和jQuery新手的新手.我有从数据库动态创建到3个不同无序列表的链接.我正在尝试将底部两个列表中的每个列表项追加到新ul标记内的顶部列表中,这将成为顶部列表中每个列表项的锚点的同级对象.我需要通过匹配href属性来做到这一点.我开始研究下面的脚本,以查看是否可以排除网址的最后一部分,以便更容易匹配href属性.任何帮助将不胜感激.
I'm new to SO and a jQuery newbie. I have links being dynamically created from a database into 3 different unordered lists. I'm trying to append list items from each of the two lists on the bottom to the the top list inside a new ul tag which will be a sibling to the anchor of each list item in the top list. I need to do this by matching the href attributes. I began playing around with the script below to see if I could exclude the last part of the the urls so it would be easier to match the href attributes. Any help would be greatly appreciated.
<script>$(document).ready(function () {
var href = $('ul.list li:nth-child(1) a').attr("href");
var n = href.lastIndexOf('/');
alert(href.substring(0, n != -1 ? n : s.length));
});
</script>
</head>
<body>
<ul class="list">
<li><a href="http://www.mysite.com/index.html">My Site</a></li>
<li><a href="http://www.google.com">Google</a></li>
<li><a href="http://www.yahoo.com">Yahoo</a></li>
<li><a href="http://www.cnn.com">CNN</a></li>
<li><a href="http://www.espn.com">ESPN</a></li>
<li><a href="http://www.tsys.com">TSYS</a></li>
</ul>
<ul class="combination">
<li><a href="http://www.mysite.com/index.html">My Site</a></li>
<li><a href="http://www.google.com">To Index Page</a></li>
</ul>
<ul class="combination2">
<li><a href="http://www.mysite.com/index.html">My Site Too</a></li>
<li><a href="http://www.yahoo.com">Yahoo Redux</a></li>
</ul>
</body>
推荐答案
类似这样的小提琴
HTML
<ul class="list">
<li><a href="http://www.mysite.com/index.html">My Site</a></li>
<li><a href="http://www.google.com">Google</a></li>
<li><a href="http://www.yahoo.com">Yahoo</a></li>
<li><a href="http://www.cnn.com">CNN</a></li>
<li><a href="http://www.espn.com">ESPN</a></li>
<li><a href="http://www.tsys.com">TSYS</a></li>
</ul>
<ul class="combination">
<li><a href="http://www.mysite.com/index.html">My Site</a></li>
<li><a href="http://www.google.com">To Index Page</a></li>
</ul>
<ul class="combination">
<li><a href="http://www.mysite.com/index.html">My Site Too</a></li>
<li><a href="http://www.yahoo.com">Yahoo Redux</a></li>
</ul>
JavaScript
Javascript
$('ul.combination li').each(function() {
var element = $('.list li a[href="' + $(this).find('a').attr('href') + '"]');
if (element.siblings('ul').length == 0) {
element.after('<ul />');
}
element.next('ul').append($(this));
})
这篇关于将锚附加到包含具有相同href属性的锚的父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!