2009-07-14 8 views
1

私は基本的にid "id_1"、 "id_2" "id_3"などを持つ複数のdivを持っています。divはすべて最初は空です。javascriptページの複数のdivにJQueryを読み込みしますか?

すべてのdivに特定のhtmlコンテンツを入力するには、ページの読み込みが必要です。しかし、私の手を煩わせるされた部分は、私はまた、HTML内で使用するための固有のID部分を抽出する必要があるということです:内側のdiv要素を印刷する内容である

<div id="id_3"> 
    <div id="inner_3></div> 
</div> 

。 '3'はjavascriptによってコンテナdiv idから抽出され、その後内部divに使用されて印刷されます。

jqueryでこれを行う方法はありますか?前もって感謝します。

$(function() { 
    $('div[id^=id_]').each(function() { 
     var id = $(this).attr('id').split('_').pop(); 
     $(this).html(
      $('<div/>').attr('id','inner_' + id) 
     ); 
    }); 
}); 

は、その後、あなたがそれぞれをループ、IDを取得し、あなたのHTMLの操作を行います。

答えて

1

あなたがstarts with特定の文字列がIDを持つすべてのdivの要素を取得することができます。

+1

優秀!まさに私が必要としたもの。ありがとう! –

0

これにはいくつかの方法がありますが、結局は単純な文字列操作です。ここに例があります:

// on page load 
$(function(){ 
    //find all divs and iterate through them - you can use any selector you like 
    $("div").each(function(){ 
     //this gets the id attribute of the div we are currently on in the loop 
     var id = $(this).attr("id"); 
     //this gets the number at the end - notice that its just string manipulation 
     var nid = id.slice(id.lastIndexOf("_") + 1) 
     //create inner div, give it an id and append 
     var innerDiv = $('div').attr("id", "inner_" + nid); 
     $(this).append(innerDiv); 
     //all done - you can append content to inner div here 
     // innerDiv.append(someContent); 
    }); 
}); 
関連する問題