表单和动态生成的按钮 JavaScript 不起作用

问题描述 投票:0回答:1

我的网站上的表格遇到问题。我有一个表单,当它最初存在于页面上时可以正常工作,但是当我尝试通过 JavaScript 动态生成此表单时,该表单在提交时不会执行任何操作。

当您按下按钮时

<button type="submit" class="generate-btn">Generate IA</button>
它不会执行任何操作

我的表单具有以下结构:

segundoDiv.innerHTML = '';

var nuevoElemento = document.createElement('section');
nuevoElemento.className = 'image-generator';
nuevoElemento.innerHTML = `
        <div class="content">
            <form action="#" class="generate-form">
                <input class="prompt-input" type="text" placeholder="Describe what you want to see" required>
                <div class="controls">
                    <button type="submit" class="generate-btn">Generate IA</button>
                </div>
            </form>
        </div>
        <section class="image-gallery">
            <div class="img-card hiddenia"><img src="images/img-1.jpg" alt="image"></div>
        </section>`;

// Agregar el nuevo elemento dentro del segundo div
segundoDiv.appendChild(nuevoElemento);

这是不运行的脚本:

<script>
const generateForm = document.querySelector(".generate-form");
const generateBtn = generateForm.querySelector(".generate-btn");
const imageGallery = document.querySelector(".image-gallery");

const OPENAI_API_KEY = "12345678910"; // Your OpenAI API key here
let isImageGenerating = false;

const updateImageCard = (imgDataArray) => {
  imgDataArray.forEach((imgObject, index) => {
    const imgCard = imageGallery.querySelectorAll(".img-card")[index];
    const imgElement = imgCard.querySelector("img");
    const downloadBtn = imgCard.querySelector(".download-btn");
        imgCard.classList.remove("hidden");

    // Set the image source to the AI-generated image data
    const aiGeneratedImage = `data:image/jpeg;base64,${imgObject.b64_json}`;
    imgElement.src = aiGeneratedImage;
    
    // When the image is loaded, remove the loading class and set download attributes
    imgElement.onload = () => {
      imgCard.classList.remove("loading");
      downloadBtn.setAttribute("href", aiGeneratedImage);
      downloadBtn.setAttribute("download", `${new Date().getTime()}.jpg`);
    }
  });
}

const generateAiImages = async (userPrompt, userImgQuantity) => {
  try {
    // Send a request to the OpenAI API to generate images based on user inputs
    const response = await fetch("https://api.openai.com/v1/images/generations", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${OPENAI_API_KEY}`,
      },
      body: JSON.stringify({
        prompt: userPrompt,
        n: 1,
        size: "1024x1024",
        response_format: "b64_json"
        
      }),
    });

    // Throw an error message if the API response is unsuccessful
    if(!response.ok) throw new Error("Failed to generate AI images. Make sure your API key is valid.");

    const { data } = await response.json(); // Get data from the response
    updateImageCard([...data]);
  } catch (error) {
    alert(error.message);
  } finally {
    generateBtn.removeAttribute("disabled");
    generateBtn.innerText = "Generate";
    isImageGenerating = false;
  }
}

const handleImageGeneration = (e) => {
  e.preventDefault();
  if(isImageGenerating) return;

  // Get user input and image quantity values
  const userPrompt = e.srcElement[0].value;
  const userImgQuantity = 1;
  
  // Disable the generate button, update its text, and set the flag
  generateBtn.setAttribute("disabled", true);
  generateBtn.innerText = "Generating";
  isImageGenerating = true;
  
  // Creating HTML markup for image cards with loading state
  const imgCardMarkup = Array.from({ length: userImgQuantity }, () => 
      `<div class="img-card loading">
        <img src="images/loader.svg" alt="AI generated image">
        <a class="download-btn" href="#">
          <img src="images/download.svg" alt="download icon">
        </a>
      </div>`
  ).join("");

  imageGallery.innerHTML = imgCardMarkup;
  generateAiImages(userPrompt, userImgQuantity);
}

generateForm.addEventListener("submit", handleImageGeneration);</script>

谢谢你的帮助

脚本未执行D

javascript html dom
1个回答
0
投票

问题可能来自于您监听表单

submit
事件的方式。您可以在页面加载时一劳永逸地完成此操作,并且只有在执行以下代码时表单已经在页面中时,这才会起作用:

const generateForm = document.querySelector(".generate-form");
// ...
generateForm.addEventListener("submit", handleImageGeneration);

一个简单的解决方案是在新表单动态添加到页面后再次执行上面的代码,以获取新表单并向其添加事件侦听器。

另一种解决方案,在页面上多次使用相同表单的情况下特别有用,是将事件侦听器委托给父元素,例如

document
并检查提交事件是否从
form
发生你真正关心的是:

// Add the listener on the `document`
document.addEventListener('submit', function(event) {
  // Check if its a form used for the image generation
  if (event.target.matches('.generate-form')) {
    // In this case run the generation
    handleImageGeneration(event);
  }
});

这是一个针对多种形式使用相同事件侦听器的示例:https://jsfiddle.net/msze18n5/5/

© www.soinside.com 2019 - 2024. All rights reserved.