如何将JavaScript添加到按钮,它将生成另一个链接到另一个页面的按钮?

时间:2017-09-24 06:41:51

标签: javascript html button

我正在尝试使用JavaScript,我可以点击按钮,它会在它上面生成一个按钮,所以例如我有第一个名为add additional的按钮:

<a href"#"><button type="button">Add Additional</button></a>

单击此按钮时,它将生成另一个按钮,我希望它显示在下面:

    <td>
         Name
   </td>
   <td>
      <a href="somewhere"><button type="button">Choose another thing</button></a>
   </td>

是否可以重复此过程,例如生成更多第二个按钮&#34;选择另一个&#34;

我希望这会让人感到困惑

5 个答案:

答案 0 :(得分:0)

为分部附加一个id / class。

<div id='my_id' >
  <td>Name</td>
  <td><button>click</button></td>
</div>

单击addMore按钮时,编写一个函数将其附加到my_id

    function onclickforaddbutton(){
        id = document.getElementById('my_id');
        var data = prompt("Enter something");  //where you can get data from user 
        id.innerHTML+="<td>"+data+"</td><td><button>Something</button></td>";
     }

答案 1 :(得分:0)

您需要先决定(容器)添加新行的位置。然后单击“添加”按钮,可以创建一个包含两列的行,用于名称和新按钮,并将该行作为容器的子项追加。

这是你如何做到的。

var count = 1;
var name = 'Generated Name';

function addNewRow() {
  var container = document.getElementById('container');
  var newRow = document.createElement('tr');
  newRow.innerHTML = "<td>" + name + (count++) + "</td><td><button>Choose another thing</button></td>"
  container.appendChild(newRow);
}
<html>

<head></head>

<body>
  <div style="padding: 2rem;">
    <table id="container">
    </table>
  </div>
  <a href="#"><button onclick="addNewRow();">Add Additional</button></a>
</body>

</html>
 

答案 2 :(得分:0)

我认为你正在寻找这样的东西!!只需添加一个脚本,这样无论何时单击按钮,它都会执行它并创建更多按钮。

<!DOCTYPE html>
<html>
<body>

<p>Click the "Add Additional" button to create a BUTTON element with a "Choose Another Thing" text.</p>

<a href="#"><button onclick="myFunction()" type="button">Add Additional</button></a>
<script>
function myFunction() {
    var x = document.createElement("BUTTON");
    var t = document.createTextNode("Choose another thing");
    x.appendChild(t);
    document.body.appendChild(x);
}
</script>

</body>
</html>

答案 3 :(得分:0)

我认为这是优雅的方式。

function appendButton(textContent, selector) {
  var button = document.createElement('button');
      button.classList.add('any');
      button.innerHTML = textContent;
  
  var selectedElement = document.querySelector(selector);
  
  return selectedElement.appendChild(button);
}


// Call this function from wherever u like
// appendButton('click here', '.container');
<div class="container">
  <button onclick="appendButton('click here', '.container')">
     Click me
  </button>
</div>

答案 4 :(得分:0)

运行此项,您将获得解决方案

<html>
<head>
<script type="text/javascript">
 function myFunction()
 {
    var a=document.createElement("a");
    a.setAttribute("href","secondpage.html");
    var btn=document.createElement("BUTTON");
    var text=document.createTextNode("Choose another thing");
    btn.appendChild(text);
    a.appendChild(btn);
    document.body.appendChild(a);
 }
</script>
</head>
<body>
<a href"#"><button type="button" onclick="myFunction()">Add 
Additional</button></a>
</body>
</html>