未捕获的ReferenceError:未定义printProducts

Uncaught ReferenceError: printProducts is not defined

本文关键字:未定义 printProducts ReferenceError      更新时间:2023-09-26

当我检查按钮的元素时,我一直收到这个错误。该按钮用于为页面提供打印视图。

HTML代码:

<button class = "hidden-print" onclick = "printProducts()">Print Products</button>

Javascript代码:

function printProducts(){
window.print();
}

附件是我在jsFiddle:中的代码

https://jsfiddle.net/PochMendoza/scj0q0dk/

在JSFiddle中,当您将包装设置为"onLoad"或"onDomready"时,您定义的函数仅在该块内部定义,外部事件处理程序无法访问

最简单的修复方法是更改:

function something(...)

收件人:

window.something = function(...)

---Niet The Dark Absol


对于您的示例,您希望定义按钮的onclick方法。使用JavaScript真的很容易,我们只需要在HTML中给按钮一个id,这样我们就可以在JavaScript代码中找到它。

更改此项:

<button class = "hidden-print" onclick = "printProducts()">Print Products</button>

对此:

<button id="myButton" class="hidden-print">Print Products</button>

请注意,我们不再需要onclick="printProducts()"部分。

现在,我们需要将printProducts函数设置为在单击按钮时运行。这可以这样做:

document.getElementById('myButton').onclick = printProducts;

开始编辑不过,为了正确运行,需要将此代码放在onload函数中
这样做:

window.onload = function() {
    document.getElementById('myButton').onclick = printProducts;
}

结束编辑

并且printProducts函数保持不变。


工作JSFiddle

document.getElementById('myButton').onclick = printProducts;
function printProducts(){
	window.print();
}
<button id="myButton" class="hidden-print">Print Products</button>