2012-02-07 8 views
4

spanの内容をtitle属性の値とともに追加しようとしています。ここで配列内の要素を含むものを追加します。

<div id="group-wrap" class="group"> 
    <span class="lbracket" title="&f">(</span> 
    <span class="grouptitle" title="&f"> Group </span> 
    <span class="rbracket" title="&f">) </span> 
    <span class="username" title="&f"> Username </span> 
    <span class="col" title="&f">:</span> 
    <span class="text" title="&f"> Helo There! </span> 
</div> 

は、私がこれまで持っているものです。

var str = []; 
    $('#group-wrap span').each(function(){ 
     str.push($(this).attr('title')); 
    }); 
    alert(str.join('')); 
}); 

http://jsfiddle.net/B9QeK/3/

出力は(各タイトル属性の値)&f&f&f&f&fですが、期待される出力が値を持って、プラススパン内のコンテンツ属性の値は、コンテンツの前に追加する必要があります。

&f(&fGroup&f)&fUsername: &f text 

この結果はどのように取得できますか?

答えて

2

あなたは、パフォーマンス上の理由として

str.push(this.getAttribute('title'), this.textContent || this.text); 

を探しているように、あなたはすべての単一の反復のためのjQueryオブジェクトを再作成するべきではありません見えます。さらに、これらの値を受け取るためにjQueryをまったく使用しないでください。

JSFiddle

ところで、あなたはもう少しエレガントにそれを行うためにjQuerys .map()の利用を行うことができます。

jQuery(function($){ 
    var str = $('#group-wrap span').map(function(){ 
     return this.getAttribute('title') + this.textContent || this.text; 
    }).get(); 

    alert(str.join('')); 
}); 

JSFiddle

リファレンス:.map()

1

ただ、各spanのテキストコンテンツを取得するためにtextメソッドを使用します。

var str = []; 
    $('#group-wrap span').each(function(){ 
     //Push value of title attribute and text content into array: 
     str.push($(this).attr('title') + $(this).text()); 
    }); 
    alert(str.join('')); 
}); 
1

あなたのライン

str.push($(this).attr('title')); 

は、次のようになります。これは作っている、が

str.push($(this).attr('title') + $(this).text()); 

2つの同一の電話$(this)があります。 IDERキャッシング:

var $this = $(this) 
str.push($this.attr('title') + $this.text()); 
2
jQuery(function($){ 
    var str = []; 
    $('#group-wrap span').each(function(){ 
     str.push($(this).attr('title') + $(this).text()); 
    }); 
    alert(str.join('')); 
}); 

Working JSFiddle

text

説明:その子孫を含むマッチした要素の集合の各要素の組み合わせテキストの内容を取得します。

docs

1
var str = ""; 
    $('#group-wrap span').each(function(){ 
     str+=$(this).attr('title')+$(this).text(); 
    }); 
    alert(str); 
}); 
関連する問題