【问题标题】:dynamically adding a button in html page with simple Javascript without any framework or library使用简单的 Javascript 在 html 页面中动态添加按钮,无需任何框架或库
【发布时间】:2022-07-01 02:45:54
【问题描述】:

嘿,我正在制作一个简单的网页,需要在最后一步下载输出图像文件.. 但我不知道如何在正确的时间动态添加下载按钮,因为在页面开始时不需要下载按钮..

所以我有 main.js 文件: 看起来像这样:

let img_code=document.getElementById('img_code');
let textbox=document.getElementById('textbox');
let gen_button_img=document.getElementById("img_button");

gen_button_qr.addEventListener("click",()=>
{
 var trailer=textbox.value;
 var url='www.example.com';
 var result= url.concat(trailer);
if (navigator.onLine)
{
    if(trailer.length<=1725 && trailer.length>0)
    {
        if((trailer !="0")&& (trailer.replace(/\s/g, '').length))
        {
            image_code.src=result;
            alert("Image Generated successfully");
      
            
            /**/
        }
        else
        {
            alert("You cannot create this file spaces only or only with single 0");
        }
    
    }
    else
    {
        alert("Maximum charecter limit is exceeded!! ");
    }
}
else
{
    alert("No Internet Connection");
}

});

所以,我的问题是有什么方法可以动态添加将文件 URL 作为输入并通过 Web 浏览器的下载器下载该文件的按钮?

注意=> 我可以通过右键单击图片并保存图像选项轻松保存结果;但我想添加一个额外的按钮来下载相同的文件。

【问题讨论】:

  • 为什么页面上没有按钮,但 CSS 中有display: none,时机成熟时只有display: block

标签: javascript html dom button htmlbutton


【解决方案1】:

cmets中解释的大部分内容,所以先阅读它

// arrow function to create and append download button into any element
// it only takes url of file that will download.
const createBtn = (URL) => {
  // create button element
  const downloadBtn = document.createElement("button");
  // you can set any name of id according to your choice
  downloadBtn.setAttribute("id", "downloadBtn");
  // create anchor element
  const downloadLink = document.createElement("a");
  // set any thing in inner text
  downloadBtn.innerText = "Download Image";
  // set download attribute to true
  downloadLink.setAttribute("download", true);
  // set url with URL 
  downloadLink.setAttribute("href", URL);
  // append button element into anchor element
  downloadLink.appendChild(downloadBtn);
  // get that element in which download button will append
  const container = document.getElementById("container");
  // append download button into any element of your choice
  container.appendChild(downloadLink);
};
// url of file
const URL = "https://images.pexels.com/photos/863963/pexels-photo-863963.jpeg?cs=srgb&dl=pexels-blaque-x-863963.jpg&fm=jpg"
// call createBtn function with URL
createBtn(URL);
<!-- The element in which download button will be appended -->
<div class="container" id="container"></div>

我不能 100% 确定这会奏效! 它也不能在堆栈 sn-p 中工作,因为 iframe 标记。 尝试在本地使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-25
    • 2020-01-16
    • 2012-06-12
    • 2014-09-17
    • 1970-01-01
    • 2021-10-20
    • 2013-08-02
    • 2022-11-17
    相关资源
    最近更新 更多