首页 > 解决方案 > 如何查找已动态创建且存在于另一个元素中的选择下拉列表的值和 ID

问题描述

我尝试使用 jquery 动态创建一个矩形,并在创建矩形后向它附加一个select drop-down,这两者都是动态完成的,并且id是动态分配给它们的。在我提交数据时创建所有必需的矩形之后,我想读取每个矩形以及每个矩形的值select。我能够获得id矩形的 ,但我无法获得每个矩形的selected值和id选择下拉列表。我尝试了一些东西,但都没有奏效,因此在这里发布相同的内容:

function to create the replica of the rectangle and append select drop-down

$('#DroppableCanvas').on('drop',function(event){
    event.preventDefault();
    var data    =   event.originalEvent.dataTransfer.getData("text/html");
    var nodeCopy = document.getElementById(data).cloneNode(true);
    nodeCopy.setAttribute("id", 'box'+NewBoxId);
    nodeCopy.classList.add('draggableAddedFields');
    nodeCopy.setAttribute("draggable",true);
    
    var SelectID        =   'select'+NewBoxId;
    var combo = $("<select></select>").attr("id", SelectID).attr("name", SelectID);
    
    $.each(BusinessStep, function (i, el) {
        combo.append("<option>" + el.text + "</option>");
    });
    
    $(nodeCopy).append(combo);
    
    event.target.appendChild(nodeCopy);
    NewBoxId++;
});

function to read each rectangle and all the added elements within each rectangle

//After adding all the drag and drop fields with values submit them
$('#SubmitFields').on('click',function(){
    var AllFields       =   [];
    $(".draggableAddedFields").each(function() {
        var obj     =   new Object();
        obj.ID      =   this.id;
        console.log($(this.id).find("select"));
        AllFields.push(obj);
    });
}) 

jQuery当我尝试执行以下操作时,我 得到了这些功能:console.log($(this.id).find("select"));

当我尝试这样做时,我变得不确定: console.log($(this.id).find("select").attr('id'));

我想在这里找到每个元素,例如在这种情况下select元素id并选择value选择下拉菜单。

由于$(this.id)属于外部矩形,我无法使用它获得价值。在大多数回复中,我搜索了他们有直接的要求,但在我的情况下,它似乎有点不同,因此发布。

标签: javascriptjqueryjquery-selectorsdynamic-programming

解决方案


To find any element inside the current one, use $(this).find instead of $(this.id).find

For getting the id and value of select dropdown inside draggableAddedFields, use this

$(".draggableAddedFields").each(function() {
       var selectId =    $(this).find("select").attr('id')
       var selectValue = $(this).find("select").val()

推荐阅读