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