0

私はJavaScriptの初心者ですが、jQueryの「each」メソッドの使用に問題があります。Joomlaサイトに、単純な画像スライダーとして機能するギャラリーモジュールがあります。リンクされた画像でライトボックスを許可するコードを追加しました。ここで実行したいのは、サムネイルキャプション(モジュールが現在追加している)をリンクのTitle属性にコピーして、各画像のライトボックスに表示されるようにすることです。

HTMLの構造は次のとおりです...

<div class="camera_wrap" id="camera_wrap_106">
<div class="cameraContents">
    <div class="cameraContent">
        <a class="camera_link" href="lightbox-large.jpg" title="This is where i need the caption"></a>
        <div class="camera_caption">
            <div>This is the caption</div>
        </div>
    </div>
    <div class="cameraContent">
        <a class="camera_link" href="lightbox-large.jpg" title="This is where i need the caption"></a>
        <div class="camera_caption">
            <div>This is the caption</div>
        </div>
    </div>
    <div class="cameraContent">
        <a class="camera_link" href="lightbox-large.jpg" title="This is where i need the caption"></a>
        <div class="camera_caption">
            <div>This is the caption</div>
        </div>
    </div>
</div>

ここまでコードを取得しましたが、各インスタンスで実行するのではなく、最初のキャプションdivを各title属性にコピーするだけです。これが最良のスタートであるかどうかはわかりません...

$("#camera_wrap_106 .cameraContent").each(function() {
    $("#camera_wrap_106 a.camera_link").attr('title', $("#camera_wrap_106 .camera_caption div").html());
});

前もって感謝します!

4

2 に答える 2

3

attr()のコールバック関数を使用できます

$("#camera_wrap_106 .cameraContent a.camera_link").attr('title',function(){
    return $.trim($(this).next().text());
});

http://jsfiddle.net/nSj8h/

または、各ステートメントを使用する場合は、セレクターでコンテキストを設定するだけです。

$("#camera_wrap_106 .cameraContent").each(function() {
    $("a.camera_link",this).attr('title', $(".camera_caption div",this).text());
});

セレクターにコンテキストを追加することは、findを使用することと同じです。

$('element',context) == $(context).find('element')

http://jsfiddle.net/baLmn/

于 2013-01-09T21:46:40.497 に答える
2

使用する必要がありますthis

$("#camera_wrap_106 .cameraContent").each(function() {
    $(this).attr('title', $(this).html());
});

.each関数のコンテキストとして反復の要素を提供します(つまりthis)。

これは2番目の引数(最初の引数はインデックス)としても提供されます。これは、次のように記述した可能性があることを意味します。

$("#camera_wrap_106 .cameraContent").each(function(index, element) {
    $(element).attr('title', $(element).html());
});
于 2013-01-09T21:43:51.177 に答える