如何使用breakline代码?

时间:2017-07-24 11:53:25

标签: javascript buttonclick

在我的代码中,我使用onclick方法获取按钮。当我动态单击此按钮时,它会显示多个带有删除按钮的文本框。所有这些过程都成功运行。但所有文本框都在不断显示。我想每行显示一个文本框。我必须添加br标签或/ n?

这是我的代码:

var button = document.getElementById('waypoint-input');

button.addEventListener("click", function() {

  var parentNode = document.getElementById('waypoints-list');

  var input = document.createElement('input');
  input.type = 'text';
  input.placeholder = 'Enter a waypoint location';
  input.id = 'waypoint' + me.waypointIndex;
  input.inputId = me.waypointIndex;
  input.name = 'waypointlist';

  input.addEventListener('input',
    function() {

      if (input.value == "") {

        var waypoint = me.waypts.filter(function(obj) {
          return obj.key === input.inputId;
        })[0];

        if (waypoint != null &&
          typeof waypoint !== "undefined") {

          var waypointIndexToRemove = me.waypts.map(
            function(el) {
              return el.key;
            }).indexOf(input.inputId);

          me.waypts.splice(waypointIndexToRemove, 1);


        }
      }
    });

  var removeInput = document.createElement('button');
  removeInput.innerHTML = 'Remove';
  removeInput.onclick = function() {
    parentNode.removeChild(input);
    parentNode.removeChild(removeInput);

    var childInputs = parentNode.getElementsByTagName('input');

    if (childInputs.length > 0) {
      for (var i = 0; i < childInputs.length; i++) {
        childInputs[i].inputId = i;
      }
    }

    if (input.value != "" && input.value != null) {

      var waypointIndexToRemove = me.waypts.map(function(el) {
        return el.key;
      }).indexOf(input.inputId);

      me.waypts.splice(waypointIndexToRemove, 1);

      for (var i = input.inputId; i < me.waypts.length; i++) {
        me.waypts[i].key = me.waypts[i].key - 1;
      }

      me.route();
    }

    me.waypointIndex--;
  }

  parentNode.appendChild(input);
  parentNode.appendChild(removeInput);

  var waypointAutocomplete = new google.maps.places.Autocomplete(
    input, {
      /*placeIdOnly : true */
    });

  me.setupPlaceChangedListener(waypointAutocomplete, 'WYPT',
    input.inputId);

  me.waypointIndex++;

}, false);

1 个答案:

答案 0 :(得分:1)

您还应在每个<br>后附加<input>代码:

parentNode.appendChild(input);
parentNode.appendChild(removeInput);
parentNode.appendChild(document.createElement('br'));

或者使用<div>包装器作为 Rajesh 提及可能更好:

var wrapper = document.createElement('div');
parentNode.appendChild(wrapper);
wrapper.appendChild(input);
wrapper.appendChild(removeInput);