【问题标题】:Functions are not defined未定义函数
【发布时间】:2014-10-01 05:25:45
【问题描述】:

我已经创建了一个include.js 文件,我将所有常规函数都放入其中。在此之前,函数位于文件本身中。

我从 Chrome 控制台收到一条错误消息,提示 changeColor() 未定义。

我不想让这里变得乱七八糟,所以我在 PasteBin 上粘贴了一些帖子。

if(username.val() == '')
{
    changeColor('#inputname');
    exclamation('#inputname');
    $.notify("U hebt geen gebruikersnaam opgegeven", "error");
    return false;
}

所以changeColor() 是未定义的,exclamation() 也是如此。现在是 Pastebin 部分:http://pastebin.com/5bbPuT4e

如您所见,我有一个 header.php 文件,其中包含了整个网站所需的所有 JS 文件。在include.js 文件中创建函数,在aanmelden.js 文件中调用函数。在我看来,我已经看不清楚了,所以我真的不知道我做错了什么。

【问题讨论】:

  • changeColor() 和 exclamation() 在您的 document...ready 函数中本地声明。它们不存在于该功能之外。虽然等待在document..ready 中调用 函数是件好事,但您不一定要在其中定义 函数。
  • 感谢您的回复和编辑我的帖子:-)。它起作用了:-)

标签: javascript jquery include


【解决方案1】:

删除 include.js 中的 document.ready。这会创建范围,因此 changeColor 和 exclamation 仅存在于包装函数中。 include.js 应该是:

 function changeColor(elem) {
            $(elem).css({
                    "border-radius": "5px",
                    "font-weight":   "bolder",
                    "border":        "1px solid red"
            });
  }           
  function exclamation(elem) {                   
          $(elem).notify(
                "-",
                        { position:"right" }
          );
  }

注意如何不再有 document.ready。

关于 javascript 中函数范围的一些信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope

【讨论】:

  • 非常感谢!成功了,我会在 5 分钟内接受你的回答 :-)
【解决方案2】:

此外,您可以扩展 jQuery 原型,以更“jQuery 方式”使用这些方法:

$.fn.extend({

  changeColor: function() {    
    return this.each(function() {
      this.css({
        "border-radius": "5px",
        "font-weight":   "bolder",
        "border":        "1px solid red"
      });
    });
  },

  exclamation: function() {
    return this.each(function() {
      this.notify("-", {position:"right"});
    });
  }

});

// Use the newly created methods like this:
$('#inputname').changeColor();
$('#inputname').exclamation();

这样您就不必担心定义函数的范围。

来源:http://api.jquery.com/jQuery.fn.extend/

【讨论】:

  • 谢谢,我不知道有这样的功能。能及时有用! :-)
猜你喜欢
  • 1970-01-01
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 2018-12-20
  • 1970-01-01
  • 2021-11-06
  • 2020-12-15
相关资源
最近更新 更多