锚标记的onclick事件未定义Javascript函数

编程入门 行业动态 更新时间:2024-10-21 13:30:36
本文介绍了锚标记的onclick事件未定义Javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在定位标记的onclick事件中,我无法访问javascript函数.

I am not able to access javascript function in onclick event of the anchor tag.

在某些情况下它可以工作,在某些情况下则不能.

In some cases it is working and in some cases , not.

任何人都可以说出发生原因的原因.

Can any body tell why it is happening.

HTML代码-

<a href='#' class="btn waves-effect waves-light bg-blue" id="startDeviceScan" onclick="call286Dart123('CollectSysInfo', '3c6c3e33bb65e8331bf4c91c0670492e');" >start device scan </a>

JavaScript函数:

Javascript function :

function call286Dart123(a,b) { console.log(a + "\t" + b); }

小提琴链接

小提琴链接

推荐答案

编辑由于@Dellirium在评论中指出了什么,因此我对答案进行了修改,以反映此处的真实问题.但是,该解决方案仍然可以使用.

EDIT Due to what @Dellirium pointed out in the comment, I've revised my answer to reflect the true issue here. The solution would still work, however.

问题在于,默认情况下,JSFiddle使JavaScript在文档加载时运行.这意味着JS是在HTML之后 加载的,因此在HTML中初始化onclick事件时将不会对其进行定义.

The problem is that JSFiddle makes the JavaScript run on document load by default. This means that the JS is loaded after the HTML, and therefore it wouldn't have been defined at the time the onclick event was initialized in the HTML.

关闭似乎是一个问题.如果您在JSFiddle中将加载类型"设置为"onload",则这是它在内部执行的操作(您可以检查开发人员控制台):

It seems to be a problem with closures. If you have "Load Type" set to "onload" in JSFiddle, this is what it does internally (you can check the developer console):

<script type="text/javascript"> //<![CDATA[ window.onload=function(){ function call286Dart123(a,b) { console.log(a + "\t" + b); } } //]]> </script>

这意味着将它包装在onload事件的匿名事件处理程序中.而且由于变量(和函数)作用域是受JavaScript中的函数约束的,因此这使得它们对全局作用域不可用

This means that it is wrapped in in an anonymous event handler to the onload event. And since variable (and function) scopes are bound by functions in JavaScript, this makes them not available to the global scope

解决方案:要解决此问题,请在"JavaScript"菜单下,将加载类型"更改为不包裹-&t; head>".就是这么简单=).

Solution: To fix this, under the "JavaScript" menu, change "Load Type" to "No wrap - in &t;head>". It's that easy =).

请参见此JSFiddle分叉作为工作示例.

换句话说,这只是将其更改为(同样,您可以通过访问我的JSFiddle上的开发人员控制台来进行验证):

In other words, this would simply change it to (again, you can verify this by visiting the developer console on my JSFiddle):

<script type="text/javascript"> //<![CDATA[ function call286Dart123(a,b) { console.log(a + "\t" + b); } //]]> </script>

其中,cal286Darkt123将在全局范围内定义(在任何其他函数之外).

In which, cal286Darkt123 would be defined in the global scope (outside any other functions).

有关闭包的更多信息,请查看 MDN文档

For more info on closures, check the MDN Docs.

更多推荐

锚标记的onclick事件未定义Javascript函数

本文发布于:2023-11-28 06:57:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641379.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   标记   事件   未定义   onclick

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!