2016-09-26 7 views
0

多くのhtmlのhref属性(タグ)に、それぞれのidの値をすぐに割り当てなければなりません。 私のコードでは、私はちょうど(最初の)値を取得します。 ありがとうございます。 2番目のパラメータで機能付き 樹里jqueryを使ってリンクのhref属性に次の要素のidを設定するには?

$(".anchor").attr("href","#"+($(".anchor").closest("div").next("div").attr("id")));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div> 
 
    <a class="anchor">Get anchor 1</a> 
 
</div> 
 
<div id="link1"> 
 
    <p>A paragraph</p> 
 
</div> 
 
<div> 
 
    <a class="anchor">Get anchor 2</a> 
 
</div> 
 
<div id="link2"> 
 
    <p>Another paragraph</p> 
 
</div>

+0

問題は解決しましたか? – Mohammad

+0

@モハマドはい、どうもありがとうございます、皆さんは最高です –

答えて

0

jqueryの.attr()、選択された要素との変化属性を繰り返します。また.parent()代わりに.closest("div")

$(".anchor").attr("href", function(){ 
 
    return "#"+$(this).parent().next("div").attr("id"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
    <a class="anchor">Get anchor 1</a> 
 
</div> 
 
<div id="link1"> 
 
    <p>A paragraph</p> 
 
</div> 
 
<div> 
 
    <a class="anchor">Get anchor 2</a> 
 
</div> 
 
<div id="link2"> 
 
    <p>Another paragraph</p> 
 
</div>

0

反復すべてのタグを有するクラスアンカーを介してループを使用して、タグのリンクを取得する$(this).parent("div").next("div").attr("id"))セレクタを使用します。

以下のスニペットを確認してください。

$(".anchor").each(function(){ 
 
    $(this).attr("href","#"+($(this).parent("div").next("div").attr("id"))); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div><a class="anchor">Get anchor 1</a> 
 
</div> 
 
<div id="link1"> 
 
<p>A paragraph</p> 
 
</div> 
 

 
<div><a class="anchor">Get anchor 2</a> 
 
</div> 
 
<div id="link2"> 
 
<p>Another paragraph</p> 
 
</div>

0

選択した要素のインスタンスが必要です。すべての.anchor要素に反復するjQueryのeach OR forwhileなどのような任意のループを使用し、それを

$(".anchor").attr("href",function(){ 
    return '#' + $(this).closest("div").next("div").attr("id"); 
}); 
関連する問題