Javascript 通过在同一div中单击按钮动态选择元素

Javascript 通过在同一div中单击按钮动态选择元素,javascript,html,forms,Javascript,Html,Forms,我正在尝试创建一个脚本,在表中添加另一行,其中包含特定的html内容。问题是,我希望在相当长的表单的每个部分上使用相同的脚本。选择表id而不必使用确切的表名,这似乎让我不知所措 这里的要点是点击“添加”按钮,它将添加该按钮所在的任何部分的附加项。但在添加它之前,我需要能够选择正确的项(表id),而无需实际使用“getElementById” 我一直在寻找答案,但对web Java脚本还是很陌生,我猜我只是不理解某些东西或尝试了错误的方法。。。如蒙协助,将不胜感激 HTML 有两个问题需要解决:

我正在尝试创建一个脚本,在表中添加另一行,其中包含特定的html内容。问题是,我希望在相当长的表单的每个部分上使用相同的脚本。选择表id而不必使用确切的表名,这似乎让我不知所措

这里的要点是点击“添加”按钮,它将添加该按钮所在的任何部分的附加项。但在添加它之前,我需要能够选择正确的项(表id),而无需实际使用“getElementById”

我一直在寻找答案,但对web Java脚本还是很陌生,我猜我只是不理解某些东西或尝试了错误的方法。。。如蒙协助,将不胜感激

HTML


有两个问题需要解决:

  • 根据您的实现,x是父div的id(字符串值),您不能对其调用“getElementsByAgename('table')。您应该获得元素引用

  • getElementsByTagName()将返回一个HTMLCollection,请尝试如下方式访问它们:children[index]

  • HTML

    <div id="div1">
      <table id="ans"></table>
      <button onClick="test(event)">test</button>
    </div>    
    

    这是问题的答案,你已经试过jQuery了吗?它有一些很好的方法,使生活更容易。您可能需要选择.closest(),它根据当前上下文选择元素。
    而且,不再需要使用笨拙的getElementById…

    您的
    myFunction
    中有一个bug。这应该会有帮助:

    在本例中,您希望找到同级表元素;可以使用
    previousSibling
    导航DOM,直到到达元素:

    function myFunction() {
      var node = event.currentTarget,
      x = node.parentNode.id;
      console.log(x);
    
      while (node && node.tagName != 'TABLE') {
        node = node.previousSibling;
      }
    
      if (node) {
        console.log(node.id);
      }
    }
    

    使用jquery追加表。
    <div id="div1">
      <table id="ans"></table>
      <button onClick="test(event)">test</button>
    </div>    
    
    function myFunction(e){
      var target = e.currentTarget.parentNode;
      //fetch id
      console.log(target.getAttribute("id"));
      //fetch table id
      console.log(target.getElementsByTagName("table")[0].getAttribute("id"));
    }
    
    function myFunction() {
      var node = event.currentTarget,
      x = node.parentNode.id;
      console.log(x);
    
      while (node && node.tagName != 'TABLE') {
        node = node.previousSibling;
      }
    
      if (node) {
        console.log(node.id);
      }
    }