在两个不同的div上使用相同功能的可能方法?

时间:2019-05-22 08:20:35

标签: javascript jquery html

我有addRow()deleteRow()函数。我为我的每个选择(无线电和复选框)粘贴了两次函数。还有其他减少方法吗?

function addRow(tableID) {
  var table = document.getElementById(tableID);
  var rowCount = table.rows.length;
  var row = table.insertRow(rowCount);
  var cell1 = row.insertCell(0);
  var element1 = document.createElement("input");

  element1.type = "checkbox";
  element1.name = "chkbox[]";
  cell1.appendChild(element1);

  var cell2 = row.insertCell(1);
  var element2 = document.createElement("input");
  element2.type = "text";
  element2.name = "txtbox[]";
  cell2.appendChild(element2);

}

function addRow1(tableID) {
  var table = document.getElementById(tableID);
  var rowCount = table.rows.length;
  var row = table.insertRow(rowCount);
  var cell1 = row.insertCell(0);
  var element1 = document.createElement("input");

  element1.type = "radiobtn";
  element1.name = "rdbtn[]";
  cell1.appendChild(element1);

  var cell2 = row.insertCell(1);
  var element2 = document.createElement("input");
  element2.type = "text";
  element2.name = "txtbox[]";
  cell2.appendChild(element2);
}

2 个答案:

答案 0 :(得分:0)

function addRow(tableID , inputType, inputName) {
  var table = document.getElementById(tableID);
  var rowCount = table.rows.length;
  var row = table.insertRow(rowCount);
  var cell1 = row.insertCell(0);
  var element1 = document.createElement("input");

  element1.type = inputType;
  element1.name = inputName;
  cell1.appendChild(element1);

  var cell2 = row.insertCell(1);
  var element2 = document.createElement("input");
  element2.type = "text";
  element2.name = "txtbox[]";
  cell2.appendChild(element2);

}
addRow(tableID, "checkbox", "chkBox[]"); //or
addRow(tableID, "radiobtn", "rdbtn[]");

您必须将属性发送到“ addRow”函数。

仔细阅读:https://medium.com/nodesimplified/javascript-pass-by-value-and-pass-by-reference-in-javascript-fcf10305aa9c

答案 1 :(得分:0)

您可以创建一个函数来创建类似以下内容的元素:

/** 
 * @param {string} tagName The name of the element to create like "input" or "div"
 * @param {Object<string, string> properties This object can be used to set properties on the 
 *        element like its name or type.
 * @param {Array<HTMLElement> [children=[]] An optional parameter to provided elements to be 
 *        added as children to the created element.
 */          
function createElement(tagName, properties, children = []) {
  // Create the element
  const element = document.createElement(tagName);
  // Get all the properties names of the properties object, iterate over all of them and 
  // set the property in the element with the provided value.
  Object.keys(properties).forEach(key => {
    element[key] = properties[key]
  });
  // Append any childeren that may have been provided.
  children.forEach(child => element.appendChild(child));
  
  // Return the element.
  return element;
}

const myElement = createElement('input', {
  type: 'checkbox',
  name: 'my-checkbox'
});
document.body.appendChild(myElement);