gpt4 book ai didi

javascript - 动态创建变量/方法名称

转载 作者:太空宇宙 更新时间:2023-11-04 15:55:17 25 4
gpt4 key购买 nike

所以这可能是我试图弄清楚的一个非常简单的问题。我发现自己不断遇到。采用以下 JavaScript/jQuery block :

 $('#image1Path').change(change => {
if(this.selectedImage1 == "None"){
$("#image1Display").attr("src", "../../assets/images/NoImageSelected.png");
} else {
$("#image1Display").attr("src", "../../assets/images/product-images/" + this.selectedImage1);
}
});

$('#image2Path').change(change => {
if(this.selectedImage2 == "None"){
$("#image2Display").attr("src", "../../assets/images/NoImageSelected.png");
} else {
$("#image2Display").attr("src", "../../assets/images/product-images/" + this.selectedImage2);
}
});

$('#image3Path').change(change => {
if(this.selectedImage3 == "None"){
$("#image3Display").attr("src", "../../assets/images/NoImageSelected.png");
} else {
$("#image3Display").attr("src", "../../assets/images/product-images/" + this.selectedImage3);
}
});

$('#image4Path').change(change => {
if(this.selectedImage4 == "None"){
$("#image4Display").attr("src", "../../assets/images/NoImageSelected.png");
} else {
$("#image4Display").attr("src", "../../assets/images/product-images/" + this.selectedImage4);
}
});

$('#image5Path').change(change => {
if(this.selectedImage5 == "None"){
$("#image5Display").attr("src", "../../assets/images/NoImageSelected.png");
} else {
$("#image5Display").attr("src", "../../assets/images/product-images/" + this.selectedImage5);
}
});

$('#image6Path').change(change => {
if(this.selectedImage6 == "None"){
$("#image6Display").attr("src", "../../assets/images/NoImageSelected.png");
} else {
$("#image6Display").attr("src", "../../assets/images/product-images/" + this.selectedImage6);
}
});

这显然是 super 重复且不必要的。当然,创建某种循环来处理它是有意义的。看起来像这样的东西:

for(i = 1; i <= 6; i++){
$("#image" + i + "Path").change(change => {
if(this.*selectedImage + i* == "None"){
$("#image" + i + "Display").attr("src", "../../assets/images/product-images/" + *this.selectedImage + i*);
} else {
$("#image" + i + "Display").attr("src", "../../assets/images/NoImageSelected.png");
}
}
}

我知道这行不通。问题当然是您不能以某种方式连接 i 变量名称和 selectedImage 变量名称,就像上面在星号之间看到的那样。我很好奇是否有某种方法可以解决这个问题,或者是否确实有一种方法可以动态创建变量/方法名称。谢谢。

最佳答案

您可以使用单个 change 处理程序,其属性以选择器开头作为 jQuery() 的参数,从 change.target.id 获取数字字符>,使用方括号表示法、字符串连接或模板文字

 const path = "../../assets/images/";
$("[id^=image]").change(change => {
let n = change.target.id.replace(/\D/g, "");
let curr = $(`#${change.target.id.replace(/Path/, "Display")}`);
let selected = this[`selectedImage${n}`];
curr.attr("src", selected == "None"
? `${path}/NoImageSelected.png`
: `${path}/product-images/${selected}`);
});

关于javascript - 动态创建变量/方法名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42756770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com