简体   繁体   English

jQuery从附加HTML的元素中获取值

[英]jQuery getting value from element with appended HTML

I am appending a table with a drag and drop library for uploading files. 我附加一个带拖放库的表来上传文件。 However when a file is dropped, I need to create a name and description for this file. 但是,当删除文件时,我需要为此文件创建名称和描述。 However, I cant seem to get the element from the text box when someone writes in the name. 但是,当有人在名称中写入时,我似乎无法从文本框中获取元素。

This is the code and my attempt. 这是代码和我的尝试。

$.each(data.files, function (index, file) {
         $('#TestTable > tbody:last-child').append('<tr><td>' + file.name + '</td><td><input id="file-upload-title' + file.name + '" type="text"></td></tr>');

            data.context = $('<button/>').text('Upload')
            .addClass("btn btn-primary start")
            .appendTo('#TestTable > tbody:last-child')
            .click(function () {
                    // This is the problem
                   alert($('#file-upload-title' + file.name).val()); = undefined
            });

        });

You can see when I append the table I use a unique ID for the file-upload-title input text object (in case there are many files) 你可以看到我附加表格的时候,我使用了一个唯一的ID作为file-upload-title输入文本对象(万一有很多文件)

How can I get the value from writing the HTML after the document has loaded? 如何在文档加载后从HTML编写中获取值?

Edit 编辑

There is a object present for $('#file-upload-title' + file.name) but not val() $('#file-upload-title' + file.name)有一个对象,但没有val()

Thanks 谢谢

Instead of hacking together a selector you can use the this keyword to reference the element which raised the event. 您可以使用this关键字来引用引发事件的元素,而不是将选择器混合在一起。 From there you can use DOM traversal methods to find the related input . 从那里你可以使用DOM遍历方法来查找相关的input You haven't shown your HTML so I can't give you a specific example, but it would be something like this: 你没有显示你的HTML所以我不能给你一个具体的例子,但它会是这样的:

// your code...
.click(function () {
    var $input = $(this).closest('tr').find('input');
    console.log($input.val());
});

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

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