JQuery在JS中工作,但不是在我的网站? [英] JQuery works in JS fiddle, but not on my website?

查看:164
本文介绍了JQuery在JS中工作,但不是在我的网站?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,真的令人沮丧和奇怪的事情正在发生。我有JQuery安装在我的服务器,我知道它正确导入,因为当我运行一个简单的...

All right, something REALLY frustrating and weird is going on. I have JQuery installed on my server, and I know it's imported correctly because when I run a simple...

$(function(){ alert('hello')});

它提醒hello。但是,当我尝试使用css选择器...

It alerts "hello." However, when I try to use a css selector...

$(。image)。css(border,3px固体红);

它不工作!是的,我100%肯定在该文件中有类名。这是真正的踢球者,当我将我的代码复制到一个 jsFiddle 它的工作很好。是什么赋予了?!

It does not work! Yes, I'm 100% sure there is something with that class name in the file. Here's the real kicker, when I COPY PASTED my code into a jsFiddle it worked just fine. What gives?!

推荐答案

您的jsFiddle设置为 onload jsFiddle窗口。如果你将它设置为No Wrap-in Head模拟< head> 标签中的代码,那么你的jsFiddle不再工作。

Your jsFiddle is set for onload in the upper left of the jsFiddle window. If you set it to "No Wrap - in Head" which simulates code in the <head> tag, then your jsFiddle no longer works.

onload 设置意味着jsFiddle在页面加载之前不运行JavaScript。

The onload setting means that jsFiddle doesn't run your javascript until the page has been loaded.

在您的实际页面中,您可能在加载网页之前运行javascript。

In your real page, you are probably running the javascript too soon before the page has been loaded.

你可以通过将你的javascript放在它自己的 .ready()函数来修复:

You can either fix that by putting your javascript in it's own .ready() function:

$(document).ready(function(){
    $(".image").css("border","3px solid red");
});






还可以确保javascript isn' t加载/运行,直到< / body> 标记之前,这是确保在脚本运行之前加载页面内容的简单方法。


Or, you can make sure the javascript isn't loaded/run until right before the </body> tag which is a simple way to make sure the content of your page is loaded before the script runs.

<body>
Your HTML content here

<script>
// your script here that runs after all of the DOM is parsed
$(".image").css("border","3px solid red");
</script>

</body>

请参阅< script>的详细信息,请参阅/ 9899701#9899701>这个回答,等效于-jquerys-ready-how-to-call-a- 标记。

See this answer for more details on placing the <script> tag appropriately.

这篇关于JQuery在JS中工作,但不是在我的网站?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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