2010-11-23 4 views
0

これが可能であるかどうかはわかりませんが、以下は私が扱っているHTMLのサンプルです。私は、jQueryを使って製品名をつかんでペアのスパンタグのIDとしてクラス "support"に挿入し、空白をアンダースコアに置き換えます。jqueryを使用して、スパンタグ内のテキストに基づいてIDを書き込みます

<div><span class="title">Product1 Name</span> <span class="support"></span></div> 
<div><span class="title">Product1 Name</span> <span class="support"></span></div> 
<div><span class="title">Product1 Name</span> <span class="support"></span></div> 
<div><span class="title">Product1 Name</span> <span class="support"></span></div> 

以下は、jQueryが変更する希望のHTMLです。これは可能ですか?

<div><span class="title">Product1 Name</span> <span class="support" id="product1_name"></span> </div> 
<div><span class="title">Product2 Name</span> <span class="support" id="product2_name"></span> </div> 
<div><span class="title">Product3 Name</span> <span class="support" id="product3_name"></span> </div> 
<div><span class="title">Product4 Name</span> <span class="support" id="product4_name"></span></div> 
+0

異なる製品名を持っていますか?彼らはすべて 'Product1 Name'を持っています。 –

答えて

4

はい。

$('span.title').each(function() 
{ 
    var $this = $(this), 
     id = $this.text().toLowerCase().replace(/ /g, '_'); 
    $this.next().attr('id', id); 
}); 

Demo!

これは非常によくしかし、重複したIDを持つ要素を作成することができます。良くない。以下のような

+0

Aww、あなたは私にそれを打つ... – Blender

+0

これは、同じdivタグの "サポート"のクラスでスパンを対象にするためにどのように修正できますか?ミックスに他のスパンタグがいくつかあるとは言いませんでした。 –

+0

@Robert: '$ this.next()'を '$ this.siblings( 'span.support')'に変更します。 http://api.jquery.com/siblings –

0

何か:あなたの「入力」はにまたがるためもしかして

(".title").each(function() {$(this).next(".support").attr("id",$(this).html().replace(" ","_"));}); 

はそれをチェックしませんでしたが、それは動作するはずです、私は括弧が最後に右カウントしまっを願って...

関連する問題