JavaScript 和 DOM
我无法理解这种情况:
我有一个网站模板,标题中有代码:
$(document).ready(function () {
$('#header').corner();
...
}
corner()
只是一个 jQuery 插件函数。但问题是:
("#header") is null
$('#header').corner();
它在主页上工作,但在另一个页面(具有相同的模板) - 不起作用。
要查看所有实际操作,请查看此页面。您将看到标题(蓝色顶部 div)四舍五入,并且 Firebug 控制台中没有任何错误。现在转到此页面。一切都正常,但这次不是主页(它仍然使用相同的模板文件)。
而第三页,错误出现在那里,但仍然是相同的模板。怎么了?
I can't understand such situation:
I have a site template and in header there is code:
$(document).ready(function () {
$('#header').corner();
...
}
corner()
is just a jQuery-plugin function. But the problem is:
("#header") is null
$('#header').corner();
It works at main page, but at another one (with the same template) - doesn't work.
To view everything in action, look at this page. You will see header (blue top div) rounded and there aren't any errors in firebug console. Now go to this page. Everything works too, but this time that's not the main page (it still uses same template file).
And the third page, the error appears there but still the same template. What's wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题是 $ 是一个愚蠢的名字a 代表函数。
第三页中,
$
由jQuery定义并由Prototype重新定义。你会遇到冲突。首先重写所有 jQuery 内容,使用
jQuery
而不是$
并调用无冲突
。The problem is that $ is a stupid name a for a function.
On the third page,
$
is defined by jQuery and redefined by Prototype. You are getting conflicts.Start by rewriting all your jQuery stuff to use
jQuery
instead of$
and callnoConflict
.一个好的解决方案是像这样对脚本使用命名空间,以避免命名冲突,正如昆汀已经提到的那样。
您仍然可以通过执行以下操作来使用 $:
这样您就不必直接使用 $,同时能够有选择地使用 $。
A good solution is to use namespacing for your scripts like this to avoid naming conflicts as Quentin already mentioned.
You can still use $ by doing the following:
This way you never have to use $ directly while being able to selectively use $.
如果您在
控制台
中输入:您会看到某些脚本在某个地方覆盖了 jQuery 快捷方式
$
。这很可能是该错误的原因。要解决这个问题,请为整个代码创建一个包装器上下文:这将保证
$
符号现在引用该函数上下文中的jQuery
对象。If you type into your
console
:You'll see that some script, somewhere overwrites the jQuery shortcut
$
. That is most likely the reason for that error. To solve that, create a wrapper context for your whole code:That will guarantee that the
$
symbol now refers thejQuery
object, within that function context.如前所述,您与 Prototype 发生了名称冲突。解决这个问题最简单的方法是:
As mentioned, you have a name collision with Prototype. The easiest way to fix this is: