I'm trying to use javascript and jquery to do some plotting, here is the code that I define the button, but the first time I click it doesn't work, the second time it works well, I don't understand why.
$('<p><input type="button" value="Plot Data" /></p>').click(getData).appendTo('#plot');
Could someone help to explai开发者_Go百科n it? Thanks!
Mengfei
var
// function for event click
getData = function(ev) {
alert('ok');
},
// your button
button = $('<input type="button" value="Plot Data" />').click(getData),
// append to p container
pcontainer = $('<p></p>').append(button).appendTo('#plot');
example
EDIT for comments
var
// counter clicks
clickCounter = 0,
// function for event click
getData = function(ev) {
$('#controlClick').append('click in getData '+(++clickCounter)+'<br />'); // firsts lines
// your code;
// don't put return false or ev.stopPropagation()
},
controlEvent = function(ev) {
$('#controlClick').append('click in control<br />');
},
// your button
button = $('<input type="button" value="Plot Data" />')
.bind('click', getData)
.bind('click', controlEvent),
// append to p container
pcontainer = $('<p></p>').append(button).appendTo('#plot');
example update
Because the click action is on 'p'. Jquery will return the object of the outer html, in your case 'p'. Try this instead:
$('#plot').append($('<p></p>').append($('<input type="button" value="Plot Data" />').wrap('').click(getData)));
Have you tried removing the "p" tags from your code?
精彩评论