简体   繁体   中英

How to add an href and img tag via JavaScript

我遇到的问题是,当我在JavaScript和img标签中添加href链接时,图像将无法显示。

html='<div id="iw-container">'+'<a ><div class="iw-title">Hot Pot Restaurant </div> </a>'+ name+"<br>"+address+"<br>"+"<img src=/"+image+'</div>';

There seemed to be a lot of typos in your code.

Please see working code below.

 let address = 'An Address'; let name = 'Persons Name'; let image = 'https://images.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'; let link = 'https://images.google.com/'; html='<div id="iw-container"><a href="'+link+'"><div class="iw-title">Hot Pot Restaurant </div> </a>'+ name+'<br>'+address+'<br><img src="'+image+'"></div>'; document.write(html); 

Try to use template literal. It is much easier and cleaner to read your code. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

 const title = "Stack Overflow"; const link = "https://stackoverflow.com"; const image= "https://streamdata.io/wp-content/uploads/2018/04/stackoverflow.png"; const html = `<div id="iw-container"> <h1><a href="${link}">${title}</a></h1><br> <img src="${image}"> </div>`; document.write(html); 

You have mixed single and double quotes and href is also missing. Try below

html = '<div id="iw-container">' + '<a ><div class="iw-title">Hot Pot Restaurant </div> </a>' + name + '<br>' + address + '<br>' + '<img src="' + image + '"></div>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM