Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 带有imgage原型的js对象构造函数_Javascript - Fatal编程技术网

Javascript 带有imgage原型的js对象构造函数

Javascript 带有imgage原型的js对象构造函数,javascript,Javascript,我试图把图像作为物体的原型之一 我错过了什么 这是我的代码: function test(prot1, prot2) { this.par1 = prot1; this.par2 = prot2; } var test1 = new test("text", "image.jpg"); document.getElementById("testdiv").innerHTML = "<img src='test1.par2' alt='test1.par1' class='image

我试图把图像作为物体的原型之一

我错过了什么

这是我的代码:

function test(prot1, prot2) {
  this.par1 = prot1;
  this.par2 = prot2;
}
var test1 = new test("text", "image.jpg");
document.getElementById("testdiv").innerHTML = "<img src='test1.par2' alt='test1.par1' class='image' />";
功能测试(prot1,prot2){
this.par1=prot1;
this.par2=prot2;
}
var test1=新测试(“text”、“image.jpg”);
document.getElementById(“testdiv”).innerHTML=“”;

在javascript中,不能简单地在字符串中键入变量并期望对其进行计算。这不管用

您需要将它们连接起来,以便将其视为变量,而不仅仅是字符串的一部分:

document.getElementById("testdiv").innerHTML = "<img src=" + test1.par2 + "alt=" + test1.par1 + " class='image' />";
document.getElementById(“testdiv”).innerHTML=“”;
或者,如果您的环境支持ES6,则可以使用字符串文字:

document.getElementById("testdiv").innerHTML = `<img src=${test1.par2} alt=${test1.par1} class='image' />`;
document.getElementById(“testdiv”).innerHTML=`;

关于后者的更多信息:

您只使用了字符串,但需要计算对象

使用ES6您可以使用

document.getElementById(“testdiv”).innerHTML=`;
对于较低版本,可以使用字符串连接

document.getElementById("testdiv").innerHTML = "<img src=" + test1.par2 + "alt=" + test1.par1 + " class='image' />";
document.getElementById(“testdiv”).innerHTML=“”;

我建议使用字符串连接
'src=“”+test1.par1+”
或模板文本
`src=“${test1.par}”`
@evolutionxbox谢谢。现在,我也知道这个操作的语法了。谢谢。现在,我也知道这个操作的语法了。谢谢。现在,我也知道这个操作的语法了。
document.getElementById("testdiv").innerHTML = "<img src=" + test1.par2 + "alt=" + test1.par1 + " class='image' />";