javascript 使用javascript进行字符串连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16293108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:05:45  来源:igfitidea点击:

string concatenation using javascript

javascripthtml

提问by vishnu

I'm trying to build a HTML string in the following way:

我正在尝试通过以下方式构建 HTML 字符串:

htmlString = '<html>';
var headerString = "image1";
var sImage = "Android_images/"+headerString+".png";
htmlString += '<img src='+sImage+' />';
htmlString = '</html>';

I need to dynamically append a image string, but it shows:

我需要动态附加一个图像字符串,但它显示:

<img src=Android_images/dfdfd.png />

采纳答案by Blender

You're re-setting the variable on this last line:

您在最后一行重新设置变量:

htmlString = '</html>';

Add a +and it'll work:

添加一个+,它会起作用:

var htmlString = '<html>';
var headerString = "image1";
var sImage = "Android_images/" + headerString + ".png";
htmlString += '<img src="' + sImage + '" />';
htmlString += '</html>';

Also, why are there <html>tags here?

另外,为什么<html>这里有标签?

回答by MervS

Try:

尝试:

var htmlString = '<html>';
var headerString = "image1";
var sImage = "Android_images/"+headerString+".png";
htmlString += '<img src="'+sImage+'" />';
htmlString += '</html>';

回答by Ripa Saha

use below code

使用下面的代码

var htmlString = '<html>';
var headerString = "image1";
var sImage = "Android_images/"+headerString+".png";
htmlString += '<img src="'+sImage+'" />';
htmlString += '</html>';

"htmlString" will contain below output

“htmlString”将包含以下输出

<html><img src="Android_images/image1.png" /></html>

think it will help you.

认为它会帮助你。

回答by Ripa Saha

var htmlString = '<html>';

htmlString += '</hmtl>';

回答by Borniet

You haven't defined htmlString as a variable before you started using it:

在开始使用 htmlString 之前,您尚未将其定义为变量:

var htmlString = '<html>';

回答by Zaheer Ahmed

you should always use var.

您应该始终使用var.

Not using var has two major drawbacks:

不使用 var 有两个主要缺点:

  • Accessing a variable within a function that is not defined within that function will cause the interpreter to look up the scope chain for a variable with that name until either it find one or it gets to the global object (accessible in browsers via window) where it will create a property. This global property is now available everywhere, potentially causing confusion and hard-to-detect bugs;
  • Accessing an undeclared variable will cause an error in ECMAScript 5 strict mode.
  • 访问函数中未在该函数中定义的变量将导致解释器查找具有该名称的变量的作用域链,直到找到一个变量或它到达全局对象(可通过窗口在浏览器中访问)在那里将创建一个属性。这个全局属性现在随处可用,可能会导致混乱和难以检测的错误;
  • 在 ECMAScript 5 严格模式下访问未声明的变量会导致错误。

Working Perfectly hereand in last line you should use +=:

在这里和最后一行完美工作,您应该使用+=

htmlString += '</html>';