jQuery存储div父ID,并从数组中删除它

时间:2014-09-10 17:50:23

标签: javascript php jquery html html5

我正在尝试动态构建输入元素,并提供添加和删除输入的选项。 我也使用php从我的数据库动态下拉该构建。 当我添加输入时,我在数组中输入父ID,当我删除输入时,我使用splice删除它。我添加或删除的每个框都包含几个输入

我也成功地将输入添加到数组并成功使用ajax传递它们,问题是当我删除1个输入时它会像循环中一样删除所有父节点。

   var x = 1
var appleTestList;
var appleinputList = new Array();

$('#applePlus').click(function(e){ //on add input button click
            var wrapper         = $("#appleDinamicBox"); //Fields wrapper
            ; //initlal text box count 
            $.ajax({
            async: false,
            type: "GET",
            url: "sqlFunctrions.php",
            data: 'func=dropDownbyValue&table=test&value=Test_ID&display=Test_Name&column=Test_Type&valueBy=Apple&selectName=appleTest&chooseFrom=Test',
            success: function(msg){
                appleTestList=msg;
            }

        }); // Ajax Call

            var htmlString='';

                x++; //text box increment
                htmlString=htmlString + '<div class="seperate" id="'+x+'"><div class="col-lg-5"><label>Test Name:</label>'; 
                htmlString = htmlString + '<select name="appleTestName'+x+'" id="appleTestName'+x+'" class="form-control"><option value=\"0\">Test</option>' +appleTestList+'</select>';
                htmlString = htmlString + '</div><div class="col-lg-5"><label>Namber Of Setups</label><input class="form-control" type="text" name="appleNumOfSetups'+x+'" id="appleNumOfSetups'+x+'"></div><img src="images/minus-s.png" id="appleMinus" class="remove_field"></div>';
                $(wrapper).append(htmlString); //add input box            

                appleinputList.push(x);

                $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
    e.preventDefault(); $(this).parent('div').remove();
    var id = $(this).parent().attr('id');
    alert(id);
    appleinputList.splice(appleinputList.indexOf(parseInt(id)),1);

            alert(id);

});

}

你能犯我的错吗,还有其他办法吗?

感谢, CFIR。

1 个答案:

答案 0 :(得分:0)

问题是每次单击$(wrapper).on("click",".remove_field"时都会绑定新的#applePlus处理程序(导致多个处理程序调用)。将此代码移出#applePlus点击处理程序。

Fiddle

$('#applePlus').click(function()
{
    var wrapper = $("#appleDinamicBox"); //Fields wrapper

    ...

    appleinputList.push(x);
});

$("#appleDinamicBox").on("click", ".remove_field", function(e){ //user click on remove text
    e.preventDefault();
    $(this).parent('div').remove();
    var id = $(this).parent().attr('id');
    appleinputList.splice(appleinputList.indexOf(parseInt(id)),1);
});