简体   繁体   English

在标签属性中调用 JavaScript function

[英]Call a JavaScript function inside tag attribute

How can we call an JavaScript function inside tag attribute?我们如何在标签属性中调用 JavaScript function ?

 let imageURL = () => 'http://www.example.com/image.png';
 <img alt="error" src="javascript:imageURL()">

src accepts only url, you can place your function here: <img alt="Not available" src="whatever" onload="this.onload=null; this.src=imageURL();"/> src只接受 url,你可以把你的 function 放在这里: <img alt="Not available" src="whatever" onload="this.onload=null; this.src=imageURL();"/>

Use JavaScript to change the image src attribute:使用 JavaScript 更改图像src属性:

 document.getElementById('myImage').src = 'https://media.wired.com/photos/5b8999943667562d3024c321/master/w_2560%2Cc_limit/trash2-01.jpg';
 <img alt="Not available" id="myImage" />

you can not run js function on attribute, try this function first it try to load placeholder, after placeholder loaded it then trigger JS function你不能在属性上运行 js function,试试这个 function 首先它尝试加载占位符,在占位符加载后触发 JS ZC1C425268E68385D1AB5074C17A94F14

<img src="https://thumbs.gfycat.com/RapidRadiantBug-small.gif" onload="this.onload=null; this.src=imageURL();" />

Use javascript to change image source, see my example:使用 javascript 更改图像源,请参见我的示例:

 document.getElementById('image').setAttribute('src', 'https://media.wired.com/photos/5b8999943667562d3024c321/master/w_2560%2Cc_limit/trash2-01.jpg');
 <img alt="Not available" src="" id="image">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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