JQuery works in JS fiddle, but not on my website?

2019-01-15 20:51发布

This question already has an answer here:

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') });

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

$(".image").css("border","3px solid red");

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?!

3条回答
【Aperson】
2楼-- · 2019-01-15 21:01
if u have a internet connection following link useful for you 

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script> 

above link put inside a body or before write a script and please verify jquery js file.
查看更多
可以哭但决不认输i
3楼-- · 2019-01-15 21:09

Have you test adding inside $(document).ready(function(){}); ?

<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script>
    $(document).ready(function(){
        $(".image").css("border","3px solid red");
    });
</script>
查看更多
可以哭但决不认输i
4楼-- · 2019-01-15 21:12

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.

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

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

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

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

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>

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

查看更多
登录 后发表回答