我有大約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」)轉換爲字符串,但這也不起作用。
這只是一個撇開,但世界已經走了jQuery瘋了。 jQuery很好,但你並不需要它來做所有事情。在很多情況下,不使用jQuery代碼更少,效率更高。例如,這個:$(this).attr(「id」);'可以是這個:'this.id;' –
謝謝@ScottMarcus,這是一個很好的觀點,我將它添加到我的代碼中。 –