按钮上的坐标单击javascript

时间:2013-02-12 07:24:52

标签: javascript jquery html

任何人都可以告诉我我错在哪里。我想点击按钮的坐标,但它给我错误

js / main.js(1):ReferenceError:找不到变量:$

按钮:

 <input type="button" style="margin-left: 80px;margin-top: 80px;"  id="theButton"  value="A button" />

J Query

 var jq = $('#theButton');
 var position = jq.offset();
 alert('x: ' + position.left + ', y: ' + position.top);

它没有给我任何东西

2 个答案:

答案 0 :(得分:1)

试试这段代码:

$(document).ready(function(){
    var jq = $('#theButton');
    var position = jq.offset();
    alert('x: ' + position.left + ', y: ' + position.top);
});

在添加jquery之前,首先在标题部分添加任意版本的main.js 像:

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

检查小提琴http://jsfiddle.net/PSpvT/

答案 1 :(得分:1)

而不是下面的内容:

var jq = $('#theButton');

尝试

var jq = document.getElementById("theButton");

jQUERY SOLUTION:

$(function() {
  var jq = $('#theButton');
 var position = jq.offset();
 alert('x: ' + position.left + ', y: ' + position.top);
});