문제

This code works fine in JSFiddle, but not locally in Chrome or Firefox. Am I doing something wrong in linking the CSS or JavaScript? In the Firefox console, I get an error that $ is undefined. Am I linking jQuery improperly?


index.html:

<!DOCTYPE HTML>
<head>
    <title>Digital Etch-A-Sketch</title>
    <link rel="stylesheet" type="text/css" href="main.css">
</head>

<body>

    <div id="wrapper">


    </div>

<script src="etch-a-sketch.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

</body>

</html>

main.css:

//Etch-A-Sketch - CSS

.square {
  float: left;
  height: 48px;
  width: 48px;
  background-color: black;
  border: 1px solid white;
}

#wrapper {
  position: relative;
  top: 50px;
  margin: 0 auto;
  height: 200px;
  width: 200px;
}

etch-a-sketch:

$(document).ready(function(){

  var wrapper = $('#wrapper');

  for (var i = 0;i < 16; i++) {
    var div = $('<div class="square"></div>');
    wrapper.append(div);
  }

});
도움이 되었습니까?

해결책

Include the jQuery library before you include your custom script:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="etch-a-sketch.js"></script>

Otherwise you're trying to use jQuery functionality before you have library available.

다른 팁

JSFIDDLE DEMO

Codepen Demo

The error lies in Jquery ! you have to use .html() to inform the jquery to extract the #wrapper from the HTML document.

By the way, this also works

Jquery :

$(document).ready(function(){
  for (var i = 0;i < 16; i++) {
    $('#wrapper').append('<div class="square"></div>');
  }
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top