【问题标题】:Using onclick to Call a Function from within another Function使用 onclick 从另一个函数中调用函数
【发布时间】:2019-06-02 15:00:57
【问题描述】:

当鼠标单击下拉列表中的菜单值时,我想识别 HTML 表格单元格。使用 W3schools 代码,我可以获得有关单元格的信息,但不能从单元格内的下拉列表中获取。 此处某处 DOM 设置不正确。

<html>
    <td onclick=myFunction5(this)>OPEN</td>
</html>

<script>
function myFunction5(x) {
   alert("Cell index is: " + x.cellIndex);
</script>

将此代码用于 HTML 表格的一个单元格:

<td id = "td01" onclick=myFunction5(this)>
    <div class="dropdown">
        <button class="dropbtn">Change?</button>
        <div class="dropdown-content">
            <p onclick = "displayTableData()">OPEN </p>          
            <p onclick = "displayTableData()">Closed</p>
        </div>
     </div>
</td>

现在我需要从另一个函数中获取单元格 ID:-

function displayTableData() {
     // when cell onclick - show cell index and contents
    var myTable = document.getElementById('t02');
    var totalRows = document.getElementById('t02').rows.length;
    var totalCol = myTable.rows[0].cells.length;

    document.getElementById(‘td01’).onclick=myFunction5(y);
    var newCellid = y.CellIndex     // return cell id 
}

alert - 单元格索引为:未定义

【问题讨论】:

  • document.getElementById(‘td01’).onclick = myFunction5(y) 将调用myFunction5(y) 的返回值分配给监听器。您尚未发布该功能的任何详细信息。 &lt;html&gt;&lt;td ...&gt;...&lt;/td&gt;&lt;/html&gt; 是无效标记,可能浏览器会将 td 包装在 table、tbody 和 tr 元素中。
  • 道歉 - 我认为 HTML 代码是不必要的。
    OPEN
    。至于不完整函数的细节——我被卡住了——我希望能够在函数中使用单元格索引,但还没有找到提取这些信息的方法。
  • 如果点击在单元格内,那么它将冒泡并调用myFunction5(this),除非您取消它。在 myFunction 中,this 将是表格单元格,它的 cellIndex 值由 cellIndex 属性显示,所以 @ 987654328@(注意大写)。

标签: javascript dom html-table onclick


【解决方案1】:

据我了解,您有一个表格单元格,里面有一个菜单结构。您希望通过单击菜单来识别菜单所在的表格单元格,这可以通过从事件目标向上移动 DOM 直到到达单元格(或用完祖先)来实现。

如果你动态附加监听器会更容易,那么监听器中的 this 将是被点击的元素。否则,您必须传递 this 或事件,例如

<p onclick="displayTableData(this)">Closed</p>

<p onclick="displayTableData(event)">Closed</p>

以下内容应该可以帮助您:

// Attach listeners
window.onload = function() {
  var nodes = document.querySelectorAll('.dropdown-content p').forEach(
    node => node.addEventListener('click', displayTableData, false)
  );
}

/* Return first ancestor of node that has tagName
** @param {HTMLElement} node - node to start from
** @param {string} tagName - tag name of element to find
** @returns {HTMLElement|undefined} - first matching ancestor or null if none found
*/
function getAncestor(node, tagName) {
  if (!node || !tagName) return;
  while (node.parentNode) {
    node = node.parentNode;
    if (node.tagName && node.tagName.toLowerCase() == tagName) {
      return node;
    }
  }
  return null;
}

function displayTableData(evt) {
  // Stop bubbling
  evt.stopPropagation();
  var cell = getAncestor(this, 'td');
  console.log(`cellIndex: ${cell && cell.cellIndex}`);
}

function myFunction5(node) {
  console.log(`myFunction5: ${node.tagName} ${node.cellIndex}`);
}
<table>
  <tr>
    <td id="td01" onclick="myFunction5(this)">
      <div class="dropdown">
        <button class="dropbtn">Change?</button>
        <div class="dropdown-content">
          <p>OPEN </p>
          <p>Closed</p>
        </div>
      </div>
    </td>
  </tr>
</table>

还有element.closest,应该有合理的支持,上面作为后备。

// Attach listeners
window.onload = function() {
  var nodes = document.querySelectorAll('.dropdown-content p').forEach(
    node => node.addEventListener('click', displayTableData, false)
  );
}

function displayTableData(evt) {
  // Stop bubbling
  evt.stopPropagation();
  var cell = this.closest('td');
  console.log(`cellIndex: ${cell && cell.cellIndex}`);
}

function myFunction5(node) {
  console.log(`myFunction5: ${node.tagName} ${node.cellIndex}`);
}
<table>
  <tr>
    <td id="td01" onclick="myFunction5(this)">
      <div class="dropdown">
        <button class="dropbtn">Change?</button>
        <div class="dropdown-content">
          <p>OPEN </p>
          <p>Closed</p>
        </div>
      </div>
    </td>
  </tr>
</table>

【讨论】:

  • 谢谢 - 这个解决方案很有魅力 - 显然最好使用 Jquery 来解决,我不熟悉但现在一直在研究。包含相关单元格的值也会很有用。我确信这一切都可以使用 Javascript 来完成,并且两者的比较对我来说会很有趣!
  • @Bobtro——使用 jQuery 的理由越来越少。我在写答案时忘记了element.closest,它可以替换 getAncestor 函数。现在大多数 DOM 工作都是使用框架完成的,而 POJS 的工作越来越少。
  • 再次感谢-这很有趣-我一直在尝试使用您的方法来获取单元格数据-打开或关闭-与单元格索引相关联-我需要将其与隔壁的关联单元格进行比较知道是否需要改变。到目前为止还没有成功 - 任何帮助将不胜感激!
  • @Bobtro——如果您有不同的问题,您应该问另一个问题。
猜你喜欢
  • 2021-09-09
  • 2011-09-19
  • 2021-08-24
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 1970-01-01
相关资源
最近更新 更多