简体   繁体   English

获取具有动态生成的 ID 的元素

[英]Obtain an element with a dynamically generated ID

I have a very straightforward thing I am trying to do, but am new to Javascript.我想做一件非常简单的事情,但我是 Javascript 的新手。

I have an HTML page which generates a series of DIV elements with an ID that is dynamically generated.我有一个 HTML 页面,它生成一系列具有动态生成的 ID 的 DIV 元素。

Example: <div id="shots_234"></div> , <div id="shots_256"></div>示例: <div id="shots_234"></div><div id="shots_256"></div>

I am making a jQuery AJAX request, and I want to populate the html with the response targetting one of those IDs.我正在发出 jQuery AJAX 请求,我想用针对其中一个 ID 的响应填充 html。

function WeddingsShotDown(shotid, segmentid) {

    document.getElementById('ShotDownId').value = shotid;

    var form = document.getElementById('ShotDown');
    var formData = new FormData(form);
    var id = "shots_" + segmentid;
    var divid = document.getElementById(id);

    console.log("Div: " + divid);

    $.ajax({
        url: '/Weddings/ShotDown',
        type: 'POST',
        data: formData,
        dataType: 'html',
        processData: false,
        contentType: false,
        success: function (response) {
            if (response) {
                $("#shots_" + segmentid).html(response);
                document.getElementById('ShotId').value = "";
                showNotification("success", "Your shot sequence has been updated", "far fa-check-circle");
            } else {
                showNotification("danger", "Error saving shot sequence", "far fa-check-circle");
            }
        }
    });
}

So neither所以两者都不是

$("#shots_" + segmentid).html(response);

Nor也不

    var id = "shots_" + segmentid;
    var divid = document.getElementById(id);

Get me the div that I want.给我我想要的 div。

How can I update that element?我怎样才能更新那个元素?

  • Var segmentid not exist in the success function. Try, save id in the request with beforeSend, and get in the receive: Var segmentid not exist in the success function。试试,用beforeSend在request中保存id,在receive中获取:
    $.ajax({
        url: '/Weddings/ShotDown',
        type: 'POST',
        data: formData,
        dataType: 'html',
        processData: false,
        contentType: false,
        beforeSend:function( jqXHR ){
            jqXHR.id = segmentid;
        }
    }).done(function(response, msgStatus, jqXHR){
        if (response) {
                $("#shots_" + jqXHR.id).html(response);
                document.getElementById('ShotId').value = "";
                showNotification("success", "Your shot sequence has been updated", "far fa-check-circle");
            } else {
                showNotification("danger", "Error saving shot sequence", "far fa-check-circle");
            }
    });

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

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