繁体   English   中英

Jquery 的克隆、文件上传和预览问题

[英]Cloned, file upload and preview issue with Jquery

我有一个克隆创建命令。 作为克隆创建的 id 参数如下(例如:id = "myid_1"),将其递增 1 并使 id = "myid_2"。 到目前为止没有问题。 这样,每个 object 都有一个唯一的 ID 值,但是这些克隆中的简单文件上传和预览 function 会导致我的 function 发生故障。

我在 jsfiddle 上创建了一个简单的示例。 https://jsfiddle.net/magecode/mbk9ps2x/12/

我在这里理解的问题是onhange事件中文件上传的id值必须与图片预览id并行增加。 为此,我求助于 attr function 并尝试并行增加 id,但它从未改变。

我想在示例中执行的代码。 值 i 始终递增,但不会添加到克隆的 object。

 <div class="clonable-block" data-toggle="cloner"> <a href="#" id="addrow" class="btn btn-info btn-block clonable-button-add" style="border-radius: 0px; font-size: 13px;"> <i class="fa fa-file pr-2"></i>Add Row</a> <div class="clonable"> <br/> <br/> <img id="upload_1" alt="your image" width="100" height="100" class="clonable-increment-id" /> <input type="file" id="preview_1" onchange="document.getElementById('upload_1').src = window.URL.createObjectURL(this.files[0])"> <br/> <br/> </div> </div>

       var i = 1;
    $("#addrow").click(function () {
        i++;

        $("#upload_" + i+"").attr("onchange", "document.getElementById('preview_'+ i + '').src = window.URL.createObjectURL(this.files[0])");

    });

我用 vanilla.js 重新创建了它,然后您可以将其转换为 Jquery。 问题是它可能会容易得多。 我推荐你 vanilla.js,它有更好的整体性能,但我理解 Jquery 的简单性。 它是这样的:

 const CloneSource = document.querySelector(".clonable-source"); const buttonRow = document.getElementById("add_row"); const clonesContainer = document.getElementById("clones"); let globalCounter = 1; // Create a globalCounter for the Form IDs window.addEventListener("change", function(e) { let target = e.target // This try catch is just for strictly saying that we // want to target the.clonable class try { let form = target.closest(".clonable") let fd = new FormData(form) let img = fd.get("img"); let preview = form.children[0] let url = URL.createObjectURL(img) preview.setAttribute("src", url); } catch { console.log("No Form") } }) buttonRow.addEventListener("click", function(e) { // Creates Form, img, and input elements let formSource = document.getElementById("source") let Form = document.createElement("form") let Img = document.createElement("img") let Input = document.createElement("input") Form.className = `clonable clonable-clone` Form.setAttribute("id", `clonable-${globalCounter}`) // This add the ID to the Form globalCounter++; // Sum 1 to the globalCounter; Img.setAttribute("src", formSource.children[0].getAttribute("src")) Input.setAttribute("type", "file") Input.setAttribute("name", "img") Form.appendChild(Img) Form.appendChild(Input) // Then append the form to the clones container clonesContainer.appendChild(Form); });
 img { width: 5rem; }
 <button id="add_row">Add Row</button> <div id="clones"> <form class="clonable clonable-source" id="source"> <img src="#"> <input type="file" name="img"> <p>Select an Image</p> </form> </div>

暂无
暂无

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

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