2017-04-16 42 views
0

我有以下代码,我想每H2id属性我会创建一个锚链接。我不能让它正常工作......jQuery:找到H2 ID和附加链接相同的ID

<div id="mydiv"> 
    <h2 id="first">first</h2> 
    <h2>second</h2> 
    <h2 id="third">third</h2> 
</div> 

.sls {color: red;font-size: 12px;} 

$('#mydiv') 
.find('h2[id]') 
.append(' <a href="http://www.test.com/page.html#'+ $('h2[id]') 
.attr('id') +'" class="sls">Link</a>'); 

https://jsfiddle.net/ivanionut/1ohh2hws/

感谢您的帮助。

回答

2

你想要这样的东西吗?

$('#mydiv').find('h2[id]').each(function() { 
 
    $(this).append(' <a href="http://www.test.com/page.html#'+ $(this).attr('id') +'" class="sls">Link</a>'); 
 
});
.sls { 
 
    color: red; 
 
    font-size: 12px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="mydiv"> 
 
\t <h2 id="first">first</h2> 
 
\t <h2>second</h2> 
 
\t <h2 id="third">third</h2> 
 
</div>

+0

太好了!现在我明白了..我将不得不使用.each()函数。非常感谢你的帮助! – Ivan

+0

不客气! ;) – Badacadabra

2

在你追加叫你正在使用$('H2 [ID])。ATTR()这将让发现该组中的第一个元素的属性,所以它总是获得第一个h2的id。使用功能更新中追加使用这个代码,就像这样:

.append(function() { 
    return '<a href="http://www.test.com/page.html#'+ $(this).attr('id') +'"class="sls">Link</a>' 
}); 

https://jsfiddle.net/1ohh2hws/2/

+0

很好。感谢您的帮助! – Ivan