2016-03-18 28 views
4

我有大約40個樣本,每個樣本都有一個ID。點擊樣本後,下面的圖片應該改變,圖片中的文字也會改變。目前我抓住了身份證,並用它來添加到圖像的URL,如下所示:使用ID調用jQuery中的變量

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

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

Thant很棒!

而且,我的劇本里我都保存爲變量的文字,像這樣:

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」)轉換爲字符串,但這也不起作用。

+3

這只是一個撇開,但世界已經走了jQuery瘋了。 jQuery很好,但你並不需要它來做所有事情。在很多情況下,不使用jQuery代碼更少,效率更高。例如,這個:$(this).attr(「id」);'可以是這個:'this.id;' –

+0

謝謝@ScottMarcus,這是一個很好的觀點,我將它添加到我的代碼中。 –

回答

3

的清潔器,更可讀的解決方案將是使用JavaScript對象,像這樣:

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,修改線如下:

$('.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

也是$('。swatches')。children('img')等於$('。swatches img'),我認爲它更乾淨。 –

+2

我沒有做一個完整的代碼審查/更新 - 我會處理這個比OP顯着不同 - 但我相信你的意見將幫助OP –

+0

感謝@cale_b。如果你有時間可以給我一個關於你如何處理這個問題的簡單解釋? –