Guys i have this function inside my script.js:

伙计们我在script.js中有这个功能:

$(document).ready(function() {
    function alert() {
      alert('AAAAAAAA');
    }
});

And i am trying to call here in my index.html:

我试图在我的index.html中调用:

$('.something').on('click', function() {
  e.preventDefault();
  alert();
});

But is showing my this error - alert is not defined.

但是显示我的错误 - 未定义警报。

But when i take off the document ready in the external script, the click handler will work. Why is that?

但是当我在外部脚本中取消文档时,单击处理程序将起作用。这是为什么?

The document ready is creating a separate scope?

准备好的文件正在创建一个单独的范围?

3 个解决方案

#1


3

Using $(document).ready() creates a new function scope (note the function() after the .ready), so when you call

使用$(document).ready()创建一个新的函数作用域(注意.ready之后的function()),所以当你调用

$(document).ready(function() {
    function alert() {
        alert('AAAAAAAA');
    }
});

alert is only defined within the document.ready block. There are two ways to solve this issue:

alert仅在document.ready块中定义。有两种方法可以解决此问题:

  1. Define the function outside of the document.ready block:

    定义document.ready块之外的函数:

    function customAlert() {
        alert('AAAAAAAA');
    }
    
  2. Attach the function to the window object:

    将函数附加到window对象:

    $(document).ready(function() {
        window.customAlert = function() {
            alert('AAAAAAAA');
        };
    });
    

更多相关文章

  1. 未捕获的ReferenceError:HTML未在HTMLTableRowElement.onclick中
  2. 如何使用ajax GET或POST方法将数据传递到amazon lambda节点。js
  3. 在each()函数内部调用多个ajax ..然后在完成所有这些操作后执行某
  4. 关于jQuery获取html标签自定义属性值或data值
  5. jquery.validate.js使用之自定义表单验证规则
  6. 加载函数加载页面但不能对数据执行任何操作
  7. 绑定和解除相同javascript函数的目的是什么?
  8. jquery自定义事件
  9. Jquery中的队列函数quene()、dequene()、clearQuene()

随机推荐

  1. 2016.5.27 php测试中敏感度高,怎么调整
  2. jsonencode添加一个空行,为什么?
  3. 如何将java中的值添加到php中?
  4. Validate PEAR包是否可以投入生产?
  5. [活动召集]福建PHP社区聚会
  6. 如何对继承对象进行单元测试?
  7. 显示长期运行的PHP脚本的进展。
  8. 如何将PHP数组的关联数组转移到javascrip
  9. 具有线程/回复的私人消息系统
  10. PHP:在类中使用数据库