简体   繁体   中英

How to give a function to an image while in a website

So I have a button that makes an image appear on a website when you click it. I want to make that image delete itself when its clicked. Is there any way I can do that? I tried:

function show_image(onclick) {
  var img = document.createElement("img");
  img.onclick = onclick;
}

show_image('delete()');

function delete() {
  style.display = 'none';
}

but that doesn't work.

You can use node.remove :

 let img = document.getElementById("img"); img.onclick = () => img.remove(); 
 <img src="img.jpg" id="img"> 

  const img = document.querySelector('img') document.querySelector('button').onclick = () => { img.style.display = 'block' } document.querySelector('img').onclick = () => { img.style.display = 'none' } 
 <button> show img </button> <img src='./border.png' /> 

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