将值传递给 onclick 匿名 JavaScript 函数

Passing a value into onclick anonymous JavaScript function

Objective:有多个 "Full Product Specifications" 按钮需要切换其各自产品规格表的可见性。最初,将所有产品规格 table 设置为不显示,然后使用按钮进行控制。无法使用 jQuery 因为... reasons/stupid 旧网站我无法完全控制...

我正在尝试使用匿名 JavaScript 函数,但我不确定如何传入我的 table?或者我什至可以?我的 JS 不是很好...

使用 jQuery 我可能只使用 .click() 和 .closest()。不确定如何翻译成纯 JavaScript,所以这就是我所拥有的。

错误...

Uncaught TypeError: Cannot set property 'display' of undefined at HTMLButtonElement.y.(anonymous function).onclick

代码...

var x = document.getElementsByClassName("pdp-full-specs-table");
console.log("There are " + x.length + " tables");
for(i = 0; i < x.length; i++){
    x[i].style.display = "none";
}

var y = document.getElementsByClassName("pdp-full-specs-toggle");
console.log("There are " + y.length + " toggles");
for(i = 0; i < y.length; i++){

    var pdpTable = x[i];
    y[i].onclick = function(pdpTable){

        // Make this a toggle later
        pdpTable.style.display = "table";
    }
}

还有 HTML 以防对任何人有帮助

<button type="button" class="btn btn-link pdp-full-specs-toggle">Full Specifications &rsaquo;</button><br>
<table class="pdp-full-specs-table">
    <tr>
        <td>Product Size</td>
            <td>some size</td>
    </tr>
</table>

一个简单、高效的解决方案是将每个元素的索引存储在元素本身上,以便在调用处理程序时,您可以通过对元素的 this 引用来引用它。

for(var i = 0; i < y.length; i++){
    y[i].__table__ = i;
    y[i].onclick = buttonHandler;
}

function buttonHandler() {
    x[this.__table__].style.display = "table";
}

有些人可能会使用闭包等来实现这一点,但没有必要这么复杂。

如果每个 button 都出现在每个 table 之前,那么您可以执行 this.nextElementSibling 来到达 table,但这在 IE8 中不起作用,并且更低。