在点击后向DOM添加菜单,后续点击仅创建列表项

时间:2016-12-21 13:27:38

标签: javascript dom

我正在构建一个Javascript菜单构建器,它允许用户通过填充输入将项目添加到菜单,然后提交数据。

这个想法是,在第一次单击时,整个菜单放在DOM中,包括第一个列表项。后续点击只会在DOM中放置<li>元素。

这是我的代码。您应该查看的函数是createForm和createMenu:

Codepen example

// track the button clicks globally
var btnClicks = 0;

// create a function the append the form to the DOM on page load.
window.onload = createForm;

function createForm() {

  // initialize out form container
  var f = formContainer();

  // declare the variables we will use in one place
  var itemName, id, className, target, href, btn, text, h2;

  // create an array that will hold the values we wish to pass to our links
  // in the menu
  var listItem = [itemName, id, className, target, href];

  // Create the labels so each input can have a unique label
  var labels = ['Name', 'ID', 'Class', 'Target', 'Link'];

  // Helper text
  h2 = document.createElement('h2');
  text = 'Fill in the fields below to create a new menu item';
  h2.innerText = text;
  f.appendChild(h2);

  // loop through the list items
  listItem.forEach(function(element, index){
    // for each element, call the createDOMNode function and pass in required data
    element = createDOMNode(labels[index], 'input', 'text', 'input_' + index);
    // append each element to the form container
    f.appendChild(element);
  });

  // create the button and give it an onclick handler
  btn = document.createElement('button');
  btn.innerText = 'Create Menu Item';
  f.appendChild(btn);
  btn.onclick = getUserInput;
}

// get what the user inputted into the fields
function getUserInput() {
  // initialize some variables and an array
  var itemName, id, className, target, href;
  item = [];

  // access the values from the input fields
  values = [
    itemName = document.getElementById('input_0').value,
    id = document.getElementById('input_1').value,
    className = document.getElementById('input_2').value,
    target = document.getElementById('input_3').value,
    href = document.getElementById('input_4').value,
  ];

  // loop through each value
  values.forEach(function(element, index){
    // and push it into the item[] array
    if(element !== '') {
      item.push(element);
    }
  });

  // make sure required items are filled out
  if(values[0] === '' && values[4] === '') {
    alert('Name and Link are both required');
  } else if(values[0] === '') {
    alert('Name is required');
  } else if(values[4] === '') {
    alert('Link is required');
  }

  // if the array is not empty, then create the menu
  if(item.length !== 0) {
    createMenu(item);
  }

  // increase the button counter
  btnClicks += 1;

}

// function to create a new menu
function createMenu(item) {
  // create elements needed for menu
  var nav = document.createElement('nav');
  var ul = document.createElement('ul');
  var li = document.createElement('li');
  var a = document.createElement('a');
  var f = document.getElementById('formContainer');

  // trying to create the nav only on the first click
  if(btnClicks < 1) {
    nav.setAttribute('class', 'nav');
    document.body.insertBefore(nav, f);
    nav.appendChild(ul);
  }

  var arrayLength = item.length;
  // loop through items and set their attributes
  for(var i = 0; i < arrayLength; i++) {
    li.appendChild(a);
    a.innerText = item[0];
    a.setAttribute('id', item[1]);
    a.setAttribute('class', item[2]);
    a.setAttribute('target', item[3]);
    a.setAttribute('href', item[4]);

  }
  // and append them to the ul
  ul.appendChild(li);
}

function formContainer() {

  // create the element and set where it is displayed in the DOM
  var formContainer = document.createElement('div');
  formContainer.setAttribute('id', 'formContainer');
  var scriptTag = document.getElementsByTagName('script')[0];
  document.body.insertBefore(formContainer, scriptTag);

  // style the element
  formContainer.style.width = '360px';
  formContainer.style.margin = '0 auto';
  formContainer.style.border = '1px solid #ddd';
  formContainer.style.padding = '15px';

  return formContainer;

}


function createDOMNode(label, element, type, id) {

  var l = document.createElement('label');
  l.innerText = label;

  // create the node and set it's type attribute
  var node = document.createElement(element);
  node.setAttribute('type', type);
  node.setAttribute('id', id);

  // style the node
  node.style.padding = '8px 4px';
  node.style.width = '100%';
  node.style.marginBottom = '10px';
  node.style.boxSizing = 'border-box';

  l.appendChild(node);

  return l;
}

1 个答案:

答案 0 :(得分:1)

每次点击按钮并向其添加新的<nav>项目时,您都会创建新的<ul><li>。您只需将创建的第一个<nav>添加到文档中,以便创建所有其他文件并从不添加。移动变量以在<nav>

之外创建<ul>function createMenu(item)

&#13;
&#13;
<script>  
// track the button clicks globally
var btnClicks = 0;

// create a function the append the form to the DOM on page load.
window.onload = createForm;

function createForm() {

  // initialize out form container
  var f = formContainer();

  // declare the variables we will use in one place
  var itemName, id, className, target, href, btn, text, h2;

  // create an array that will hold the values we wish to pass to our links
  // in the menu
  var listItem = [itemName, id, className, target, href];

  // Create the labels so each input can have a unique label
  var labels = ['Name', 'ID', 'Class', 'Target', 'Link'];

  // Helper text
  h2 = document.createElement('h2');
  text = 'Fill in the fields below to create a new menu item';
  h2.innerText = text;
  f.appendChild(h2);

  // loop through the list items
  listItem.forEach(function(element, index){
    // for each element, call the createDOMNode function and pass in required data
    element = createDOMNode(labels[index], 'input', 'text', 'input_' + index);
    // append each element to the form container
    f.appendChild(element);
  });

  // create the button and give it an onclick handler
  btn = document.createElement('button');
  btn.innerText = 'Create Menu Item';
  f.appendChild(btn);
  btn.onclick = getUserInput;
}

// get what the user inputted into the fields
function getUserInput() {
  // initialize some variables and an array
  var itemName, id, className, target, href;
  item = [];

  // access the values from the input fields
  values = [
    itemName = document.getElementById('input_0').value,
    id = document.getElementById('input_1').value,
    className = document.getElementById('input_2').value,
    target = document.getElementById('input_3').value,
    href = document.getElementById('input_4').value,
  ];

  // loop through each value
  values.forEach(function(element, index){
    // and push it into the item[] array
    if(element !== '') {
      item.push(element);
    }
  });

  // make sure required items are filled out
  if(values[0] === '' && values[4] === '') {
    alert('Name and Link are both required');
  } else if(values[0] === '') {
    alert('Name is required');
  } else if(values[4] === '') {
    alert('Link is required');
  }

  // if the array is not empty, then create the menu
  if(item.length !== 0) {
    createMenu(item);
  }

  // increase the button counter
  btnClicks += 1;

}
var nav = document.createElement('nav');
var ul = document.createElement('ul');
// function to create a new menu
function createMenu(item) {
  // create elements needed for menu
  var li = document.createElement('li');
  var a = document.createElement('a');
  var f = document.getElementById('formContainer');

  // trying to create the nav only on the first click
  if(btnClicks < 1) {
    nav.setAttribute('class', 'nav');
    document.body.insertBefore(nav, f);
    nav.appendChild(ul);
  }

  var arrayLength = item.length;
  // loop through items and set their attributes
  for(var i = 0; i < arrayLength; i++) {
    li.appendChild(a);
    a.innerText = item[0];
    a.setAttribute('id', item[1]);
    a.setAttribute('class', item[2]);
    a.setAttribute('target', item[3]);
    a.setAttribute('href', item[4]);

  }
  // and append them to the ul
  ul.appendChild(li);
}

function formContainer() {

  // create the element and set where it is displayed in the DOM
  var formContainer = document.createElement('div');
  formContainer.setAttribute('id', 'formContainer');
  var scriptTag = document.getElementsByTagName('script')[0];
  // document.body.insertBefore(formContainer, scriptTag);
  document.body.appendChild(formContainer);

  // style the element
  formContainer.style.width = '360px';
  formContainer.style.margin = '0 auto';
  formContainer.style.border = '1px solid #ddd';
  formContainer.style.padding = '15px';

  return formContainer;

}


function createDOMNode(label, element, type, id) {

  var l = document.createElement('label');
  l.innerText = label;

  // create the node and set it's type attribute
  var node = document.createElement(element);
  node.setAttribute('type', type);
  node.setAttribute('id', id);

  // style the node
  node.style.padding = '8px 4px';
  node.style.width = '100%';
  node.style.marginBottom = '10px';
  node.style.boxSizing = 'border-box';

  l.appendChild(node);

  return l;
}

</script>
&#13;
&#13;
&#13;