2014-07-02 73 views
-2

今天刚开始学习这种语言(我很抱歉,如果这是一个愚蠢的问题),但我想弄清楚如何将圆圈插入到网页上。我在这里找到了一个示例代码:http://jsfiddle.net/7xQZ2/ 但是,当我尝试从单个文件运行它时,由于某种原因,脚本部分未运行。我试着改变<body><script>。它只是显示一个坐标为(0,0)的框。它保持静态,当我移动鼠标时它不会改变。使用jQuery插入鼠标点击圈

<!DOCTYPE html> 

<html> 
<head> 
    <h2 id="status2">0, 0</h2> 
    <canvas width="500px" height="500px" style="width: 500px; height: 500px; border:1px ridge green;" id="special"> 
    </canvas> 
</head> 

<body> 
    <script> 
     jQuery(document).ready(function(){ 
      $("#special").click(function(e){ 

       var x = e.pageX - this.offsetLeft; 
       var y = e.pageY - this.offsetTop; 

       /* var c=document.getElementById("special"); */ 
       var ctx= this.getContext("2d"); /*c.getContext("2d");*/ 
       ctx.beginPath(); 
       ctx.arc(x, y, 10,0, 2*Math.PI); 
       ctx.stroke(); 
       $('#status2').html(x +', '+ y); 
      }); 
     }) 
    </script> 
</body> 

</html> 
+0

HTML位于body标签和脚本之间的head标签之间。 – j08691

+0

wh-为什么你的身体内容在你的''标签中? – Jnatalzia

+0

首先,你依赖于jQuery库,并没有包含它。其次,你有无效的HTML,因为你有中的元素。把它们弄清楚,它可能会起作用。 –

回答

1

您需要包含jQuery。请将这条线在head部分:

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

也动你有什么地方在headbody,反之亦然。

+0

请设置一个答案为已接受。 –

0

您的代码使用jQuery库。在使用你的代码之前一定要包含它。

而且,这将是在你的页面中的所有HTML元素必须在身体标签,而不是之一。

<!DOCTYPE html> 
<html> 
<body> 
    <h2 id="status2">0, 0</h2> 
    <canvas width="500px" height="500px" style="width: 500px; height: 500px; border:1px ridge green;" id="special"> 
    </canvas> 
    <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> 
    <script> 
     jQuery(document).ready(function(){ 
      $("#special").click(function(e){ 

       var x = e.pageX - this.offsetLeft; 
       var y = e.pageY - this.offsetTop; 

       /* var c=document.getElementById("special"); */ 
       var ctx= this.getContext("2d"); /*c.getContext("2d");*/ 
       ctx.beginPath(); 
       ctx.arc(x, y, 10,0, 2*Math.PI); 
       ctx.stroke(); 
       $('#status2').html(x +', '+ y); 
      }); 
     }) 
    </script> 
</body> 
</html> 
0

如果你只这让作为你的HTML

<!DOCTYPE html> 

<html> 
<head> 
    <h2 id="status2">0, 0</h2> 
    <canvas width="500px" height="500px" style="width: 500px; height: 500px; border:1px ridge green;" id="special"> 
    </canvas> 
</head> 

<body> 
    <script> 
     jQuery(document).ready(function(){ 
      $("#special").click(function(e){ 

       var x = e.pageX - this.offsetLeft; 
       var y = e.pageY - this.offsetTop; 

       /* var c=document.getElementById("special"); */ 
       var ctx= this.getContext("2d"); /*c.getContext("2d");*/ 
       ctx.beginPath(); 
       ctx.arc(x, y, 10,0, 2*Math.PI); 
       ctx.stroke(); 
       $('#status2').html(x +', '+ y); 
      }); 
     }) 
    </script> 
</body> 

</html> 

然后是的,这是行不通的。因为你使用的代码属于JavaScript的jQuery库。这需要你在你的代码中包含jQuery。它不是内置在每个浏览器中。

使用此代码来添加它。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>