Onclick功能“未定义” [英] Onclick function "is not defined"

查看:150
本文介绍了Onclick功能“未定义”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对wordpress很新,我正在尝试定义和调用函数但无法使其工作。

I am fairly new to wordpress and am trying to define and call a function but cannot get it to work.

以下代码出现在php文件中使用get_template_part从content.php文件调用。

The following code appears in a php file that is called from the content.php file using get_template_part.

<div onclick="checkAllTopicCheckBoxes()"> </div>

我将以下代码添加到function.php文件的底部:

I added the following code to the bottom of the function.php file:

function checkAllTopicCheckBoxes() {
    alert("Hello! I am an alert box!!");
}

当我点击它返回的元素时:

When I click the element it returns:


(index):363未捕获的ReferenceError:未定义checkAllTopicCheckBoxes。

(index):363 Uncaught ReferenceError: checkAllTopicCheckBoxes is not defined.

任何人都可以帮助我吗?

Can anyone please help me?

推荐答案

使用OnClick或类似属性是非常糟糕的做法。

Using OnClick or similar attributes is very poor practice.

使用Javascript事件监听器是一种更好的方法。
以现代方式注册活动是处理事件的不显眼的方式。另外,要为目标注册多个事件侦听器,可以为同一目标调用addEventListener()。

Using Javascript Event Listener is a much better way of doing this. Registering an event in a modern way is the unobtrusive way of handling events. Also to register more than one event listener for the target you can call addEventListener() for the same target.

HTML:

<div id="checkAllTopicCheckBoxes"> </div>

您的JavaScript应该如下所示:

Your JavaScript is supposed to look like this:

document.getElementById ("checkAllTopicCheckBoxes").addEventListener ("click", myFunction, false);

function myFunction() {
  alert("Hello! I am an alert box!!");
}

HTML属性(例如Onclick)应该是避免因为它涉及的内容/结构和行为没有很好地分离,使得更难找到bug。

HTML attribute (such as Onclick) should be avoided as it concerns the content/structure and behavior are not well-separated, making a bug harder to find.

这篇关于Onclick功能“未定义”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆