2016-03-18 6 views
4

私はIDを持つ約40個の見本を持っています。スウォッチをクリックすると、下の画像が変化し、画像内のテキストも同様に変化します。現在のところ、私はIDをつかんで、そのように画像のURLに追加しています。IDを使用してjQueryで変数を呼び出す

$('.swatches').children('img').click(function(){ 
    var clickedId = $(this).attr("id"); 

    $('#wallPic').attr('src', '//somepathtogettothisimage/theproductname_' + clickedId'); 
    }) 

Thant works素晴らしいです!

var firstText = "Text for the first image", 
    secondText = "Some other kind of text", 
    thirdText = "Yet more text that's really different from the other two"; 

idが「テキスト」は、それに追加された変数と一致したので、私は、私はちょうど何ができると仮定:

また、私のスクリプト内で私のようなので、変数として保存されているテキストのすべてを持っています以下のようなものは:私が想定し

$('.swatches').children('img').click(function(){ 
    var clickedId = $(this).attr("id"); 
    var newText = clickedId + "Text" 

    $('#wallPic').attr('src', '//somepathtogettothisimage/theproductname_' + clickedId); 
    $('#imageText').html(newText); 

    }) 

、この場合には、 "をnewTextは、" グローバル変数( "firstText"、 "secondText"、 "thirdText" など)を参照することになります。しかし、ダイスはありません。

IDをグローバル変数を参照してテキストを変更する方法はありますか?ある時点で、私は新しいテキスト変数( "newText")を文字列に変換しようとしましたが、それもうまくいきませんでした。

var imageTexts = {}; 
imageTexts['first'] = "Text for the first image"; 
imageTexts['second'] = "Some other kind of text"; 
imageTexts['third'] = "Yet more text that's really different from the other two"; 

を次に、あなたのjQueryで、次のように行を変更します:

+3

これはただでありますさて、世界はjQueryが狂ってしまった。 jQueryは素晴らしいですが、すべてを実行する必要はありません。場合によっては、コードが少なく、jQueryを使用しない方が効率的です。例えば、次のようになります: '$(this)).attr(" id ");' this:id; ' –

+0

ありがとう@ScottMarcus、それは素晴らしい点です。 –

答えて

3

クリーナー、より読みやすいソリューションはそうのように、JavaScriptのオブジェクトを使用することです

$('.swatches').children('img').click(function(){ 
    var clickedId = $(this).attr("id"); 
    $('#wallPic').attr('src', '//somepathtogettothisimage/theproductname_' + clickedId); 
    // Reference "imageTexts" with the clickedID (assuming 'first', 'second', etc) 
    $('#imageText').html(imageTexts[clickedId]); 

    }) 
+1

また、$( '。スウォッチ')。子供( 'img')は$( '。スウォッチimg')と同等です。 –

+2

私は完全なコードレビュー/アップデートを行っていません - これはOPとは大きく異なるアプローチになりますが、あなたのコメントがOPに役立つと確信しています。 –

+0

Thanks @cale_b。あなたが一瞬を持っていたら、これにどうやってアプローチするのかを簡単に説明できますか? –

関連する問題