简体   繁体   English

如何为动态添加到网站的按钮创建 function? 香草 Javascript

[英]How to create a function for a button that is dynamically added to the website? Vanilla Javascript

Hi so I'm creating this Image Upload feature but I'm stuck with the logic of creating a function for the dynamically added call to action buttons .嗨,我正在创建此图像上传功能,但我坚持为动态添加的号召性用语按钮创建 function 的逻辑 So I have this drag and drop upload image, and when you drop the image in the drop-area it'll automatically display a preview of the image and that preview image has a button below in it, a Remove Button所以我有这个拖放上传图像,当你将图像拖放到拖放区域时,它会自动显示图像的预览,并且该预览图像下面有一个按钮,一个删除按钮

const previewImage = function(file) {
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {        
    let div = document.createElement('div');
    div.className = 'preview-image-result';
    div.innerHTML = `
      <img src="${reader.result}">
      <div class="d-flex justify-content-center">
        <span class="remove-image-button" onclick="removeImage()">Remove Image</span>
      </div>
    `;
  }
  document.getElementById('preview-image-container').prepend(div);
}

I tried to add a onclick=removeImage() in the <span> but it returns error and says (index):1 Uncaught ReferenceError: removeImage is not defined I assume that since the <span>Remove Image</span> is dynamically added to the site it is not detecting the removeImage() method I created.我试图在<span>中添加一个onclick=removeImage()但它返回错误并说(index):1 Uncaught ReferenceError: removeImage is not defined我假设因为<span>Remove Image</span>是动态添加的到该站点,它没有检测到我创建的removeImage()方法。 Anyone can help me on what method to use in this kind of workflow or am I missing something?任何人都可以帮助我在这种工作流程中使用什么方法,或者我错过了什么? using Vanilla Javascript使用香草 Javascript

const removeImage = function() {
 // remove image
}

An event listener on the document will do:文档上的事件侦听器将执行以下操作:

document.addEventListener("click", function(event){
  if(event.target.classList.contains("remove-image-button"){
    event.target.closest(".preview-image-result").remove();
  }
})

So if any click on the document occurs and the clicked element has the remove-image-button class, its preview-image-result parent will be removed.因此,如果发生对文档的任何点击并且被点击的元素具有remove-image-button class,则其preview-image-result父级将被删除。

Adding an event listener to the document and checking for specific condition of the clicked element is also called event delegation .向文档添加事件侦听器并检查单击元素的特定条件也称为事件委托

I see, thanks for pointing it out on the comments.我明白了,感谢您在评论中指出这一点。 The removeImage() is placed inside of the jQuery(document).ready(function () { }) I change the placement of the removeImage() outside of the jQuery(document).ready(function () {}) and It works! removeImage() removeImage()jQuery(document).ready(function () { })内!

const removeImage = function() {
  // remove image
}

jQuery(document).ready(function () {
const previewImage = function(file) {
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {        
    let div = document.createElement('div');
    div.className = 'preview-image-result';
    div.innerHTML = `
      <img src="${reader.result}">
      <div class="d-flex justify-content-center">
        <span class="remove-image-button" onclick="removeImage()">Remove Image</span>
      </div>
    `;
  }
  document.getElementById('preview-image-container').prepend(div);
}
})

I can't tell if the dynamic part of OP code actually works so in the example below the img has been added dynamically.我不知道 OP 代码的动态部分是否真的有效,所以在下面的示例中, img是动态添加的。 The event handler removeImg(e) has been bound to an ancestor element <section> .事件处理程序removeImg(e)已绑定到祖先元素<section> Through event delegation, any button of any amount can be controlled as long as it's within the <section> .通过事件委托,任何数量的按钮都可以被控制,只要它在<section>内。 The event handler has been designed only to react to any click on .btn and nothing else.事件处理程序被设计为仅对.btn上的任何点击做出反应,没有其他反应。

 const sec = document.querySelector('section'); const previewImage = () => { let img = ` <figure class="d-flex justify-content-center"> <img src="https://i.ibb.co/hZj77BZ/lena01.jpg" width='150'><figcaption><button class="btn">Remove Image</button></figcaption></figure> `; sec.insertAdjacentHTML('afterBegin', img); } previewImage(); const removeImg = e => { const btn = e.target; if (btn.matches('.btn')) { let imgFrame = btn.closest('figure'); imgFrame.remove(); } }; sec.onclick = removeImg;
 <section></section>

暂无
暂无

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

相关问题 如何在 vanilla JavaScript 中动态创建嵌套的 object - How to dynamically create nested object in vanilla JavaScript 处理使用“香草” javascript动态添加的HTML元素 - Manipulate HTML elements added dynamically with 'vanilla' javascript 使用香草JavaScript模仿对动态添加的元素的点击 - Imitating a click on a dynamically added element with vanilla JavaScript Vanilla Javascript 如何在事件监听器上覆盖添加 function? - Vanilla Javascript how override added function on event listener? 如何编写一个 function 来创建一个按钮并打印出没有 jQuery 的 vanilla javascript 的值? - How to write a function to create a button and print out the value with vanilla javascript without jQuery? Vanilla JavaScript:如何动态创建一个在用户选择了一些文本后显示的按钮,然后对该文本执行一些操作? - Vanilla JavaScript: How to dynamically create a button that shows up after user has selected some text and then do something with that text? 如何在使用Vanilla JavaScript的打字游戏上创建正确的开始按钮 - How to create a proper start button on typing game using vanilla javascript 当JavaScript动态添加行时,单选按钮功能无法正常工作 - Radio button function not working properly when rows dynamically added by javascript onclick 在动态添加香草 javascript 时自动启动 - onclick automatically fires up when dynamically added with vanilla javascript 如何在 vanilla JavaScript 中创建持续时间? - How to create duration in vanilla JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM