如何修复javascript中的appel功能

时间:2019-04-16 14:50:33

标签: javascript jquery

我正在动态表单上添加很多选择,然后将那些片断注入我的数组中,添加效果很好,但是删除似乎无法正常工作,因此当我尝试使用2或3个select选择时,它似乎可行很好,但是当我添加4或5个选择并尝试删除第3个选择时,remove函数会执行多次,这会影响数组的结果。

html

<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->

<div class="container">
    <div class="row">
        <p id="count"  ></p>
        <div class="control-group" id="fields">
            <label class="control-label" for="field1">Fields</label>
            <div class="controls" id="profs"> 
                <form class="input-append">
                    <div class="form-group">

    <select class="custom-select mr-sm-2" id="field1">
        <option selected>...</option>
      <option>service1</option>
      <option>service2</option>
      <option>service3</option>
      <option>service4</option>

    </select>
  </div>
                    <button id="b1" class="btn add-more" type="button">+</button></div>
                    <!--<div id="field"><input autocomplete="off" class="input" id="field1" name="prof1" type="text" placeholder="Type something" data-items="8"/>

js

  $(document).ready(function(){
    var next = 1;
    var selection=['service1','service2','service3',"service4"];
    var listService=[];//[{'id':next,'target_service':$('#field1').val()}];
    console.log(listService);
    $(".add-more").click(function(e){
        e.preventDefault();
        var addto = "#field" + next;
        var addRemove = "#field" + (next);
        next = next + 1;
        var newIn = '<id="field" ><label>';
        //newIn+='Veuillez choisir un service</label>';
        newIn+='<select class="custom-select mr-sm-2" id=field'+next+'>';
        newIn+=' <option selected>...</option>';
        for(var i=0;i<selection.length;i++){
            newIn+='<option>'+selection[i]+'</option>';
        }
        newIn+=' </select></div>';

        var newInput = $(newIn);
        var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn-danger remove-me" >-</button></div><div id="field">';
        var removeButton = $(removeBtn);

        $(addto).after(newInput);
        $(addRemove).after(removeButton);
        $("#field" + next).attr('data-source',$(addto).attr('data-source'));
        $("#count").val(next);
        var value=$('#field'+(next-1)).val();
        listService.push({'id':next,'target_service':value});
        console.log(listService);

            $('.remove-me').click(function(e){
                e.preventDefault();
                var fieldNum = this.id.charAt(this.id.length-1);
                var fieldID = "#field" + fieldNum;
                $(this).remove();
                $(fieldID).remove();

                listService.splice(fieldNum-1, 1);
                console.log(fieldNum);
                console.log(listService);
            });


    });



});

1 个答案:

答案 0 :(得分:0)

您的代码有两个问题: 您要将click事件处理程序绑定到另一个事件处理程序中,这就是第二个事件多次触发的原因。分开两个事件。

第二,将两个事件分开时,您需要使用event delegation,因为您要将第二个事件绑定到可能不存在的元素。为此,我将// Example program #include <iostream> #include <string> #include <vector> #include <map> using namespace std; int main() { vector<long> v1 = {10,2,3}; vector<long> v2 = {20,3,4}; map <double, vector<long>> correlationValues1; correlationValues1.insert(pair<double, vector<long>>(10.0, v1)); correlationValues1.insert(pair<double, vector<long>>(5.0, v2)); vector<long> finalDirections1 = (correlationValues1.rbegin())->second; } 函数更改为.on()

.click
$(document).ready(function() {
  var next = 1;
  var selection = ['service1', 'service2', 'service3', "service4"];
  var listService = []; //[{'id':next,'target_service':$('#field1').val()}];
  console.log(listService);
  $(".add-more").on('click', function(e) {
    e.preventDefault();
    var addto = "#field" + next;
    var addRemove = "#field" + (next);
    next = next + 1;
    var newIn = '<id="field" ><label>';
    //newIn+='Veuillez choisir un service</label>';
    newIn += '<select class="custom-select mr-sm-2" id=field' + next + '>';
    newIn += ' <option selected>...</option>';
    for (var i = 0; i < selection.length; i++) {
      newIn += '<option>' + selection[i] + '</option>';
    }
    newIn += ' </select></div>';

    var newInput = $(newIn);
    var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn-danger remove-me" >-</button></div><div id="field">';
    var removeButton = $(removeBtn);

    $(addto).after(newInput);
    $(addRemove).after(removeButton);
    $("#field" + next).attr('data-source', $(addto).attr('data-source'));
    $("#count").val(next);
    var value = $('#field' + (next - 1)).val();
    listService.push({
      'id': next -1 , //changed the ID to match the actual value
      'target_service': value
    });
    console.log(listService);

  });

  $(document).on('click', '.remove-me', function(e) { //moved this outside the first event 
                                                     // handler and used event delegation
    e.preventDefault();
    var fieldNum = this.id.charAt(this.id.length - 1);
    var fieldID = "#field" + fieldNum;
    $(this).remove();
    $(fieldID).remove();

    // we have to iterate over the array in case the items are not deleted in order
    for( var i = 0; i < listService.length; i++){ 
   		    if ( parseInt(listService[i].id)  === parseInt(fieldNum)) {
 		    listService.splice(i, 1);
   		    }
	}
    console.log(fieldNum);
    console.log(listService);
  });


});