Javascript 使用ID在jQuery中调用变量

Javascript 使用ID在jQuery中调用变量,javascript,jquery,Javascript,Jquery,我有大约40个样本,每个样本都有一个id。单击样本后,下面的图像应该会改变,图像中的文本也会改变。目前我正在抓取id并使用它添加到图像的URL中,如下所示: $('.swatches').children('img').click(function(){ var clickedId = $(this).attr("id"); $('#wallPic').attr('src', '//somepathtogettothisimage/theproductname_' + clic

我有大约40个样本,每个样本都有一个id。单击样本后,下面的图像应该会改变,图像中的文本也会改变。目前我正在抓取id并使用它添加到图像的URL中,如下所示:

$('.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";
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";
添加“Text”时,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”)转换为字符串,但也没有成功。

更干净、更可读的解决方案是使用javascript对象,如下所示:

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";
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]);

  })

另外,$('.swatches').children('img')等于$('.swatches img'),我认为这更干净。我没有进行完整的代码审查/更新-我的做法与OP有很大不同-但我相信您的评论将有助于OPThank@cale_b。如果你有时间,你能给我一个简短的解释你将如何处理这个问题吗?这只是一个旁白,但这个世界已经变得疯狂了。jQuery很好,但您不需要它来做所有事情。在可能的情况下,不使用jQuery的代码更少,效率更高。例如,this:
$(this.attr(“id”)
可能就是这样:
this.id谢谢@ScottMarcus,这是一个很好的观点,我将把它添加到我的代码中。