jQuery mouse position and calling click events of dynamically created elements
jQuery("body").dblclick(function(event){
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
j开发者_JAVA技巧Query("<div></div>").addClass("node").css("position","absolute")
.css("top",x).css("left",y).bind("click",showOptions).appendTo("body");
var showOptions = function()
{
alert("santa clara");
}
});
I have two problems here one is that I am not able to get the mousePositions right. Other is that I am wishing to call function showOptions
on click of dynamically created div that's not happening.
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
The document.body
has no offsetLeft
and offsetTop
as it is the page itself - it starts at (0, 0)
. Don't you simply want event.pageX
and Y
perhaps? That will also correspond with position: absolute
pixels.
Secondly, you define yourshowOptions
function after you assign it to .bind
. So it's not available yet.
I also added some tricks so that the code is a little more readable:
jQuery("body").dblclick(function(event){
var showOptions = function()
{
alert("santa clara");
};
var x = event.pageX,
y = event.pageY;
jQuery("<div>").addClass("node")
.css({position: "absolute",
left: x,
top: y })
.click(showOptions)
.appendTo("body");
});
- Define
showOptions
first - Use a function declaration rather than a function expression]1
- There is a simpler syntax for creating DOM elements
$('body').click(function (event)
{
var x = event.pageX - this.offsetLeft,
y = event.pageY - this.offsetTop;
function showOptions()
{
alert('santa clara');
}
$('<div/>',
{
'class': 'node',
css: {
position: 'absolute',
top: x,
left: y
},
click: showOptions
}).appendTo(this);
});
精彩评论