Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click() not working on replaced html

I am trying to create a go-moku game using jquery,php, and mysql database. I have a ajax function that updates the a board every second if needed.

var turnCount = -1;
setInterval(function(){
    $.get('includes/boardControl.php',{turn: turnCount }, function(data){
        if(data != "")
        {   $("#board").html(data);
            turnCount = $("#turnCount").text();
            $("#turnCount").text("")
        }
    });

}, 1000);

This works just fine, it checks the database to see if turn has been incremented and replaces the board if it has. Now what I want to ultimately do is create a click function that use Ajax to update the board and turn count in the database. I am hoping to somehow use the N'th selector do determine what square I'm clicking on.

I have several questions.

1) My click function right now is

$(document).ready(function() {
    $("td > img").click(function(){
        alert("clicked");
    });
});

as of right now it works on a extra test table I wrote into the html, but not on the table created with the previous function. What am I doing wrong?

2) The tutorials I've looked at so far dictate that I should write code in the following way.

$(document).ready(function() {
  //code here
});

When i asked a question last night, I was told that I was over complicating things with my functions. So when should i use a document.ready function and when not? And is it fine to put all of my scripts into one document.ready function or should I have multiple?

3) Once I get the click image to work I am hoping to send a X,Y coordinate to the server and change that corresponding spot on the board. How would I determine what cell in the table is clicked in order to know what coordinates to use? (or is there a much easier way?)

like image 858
Bolt_Head Avatar asked Oct 01 '09 00:10

Bolt_Head


1 Answers

sounds like you need to change

$("td > img").click(function(){
                alert("clicked");
        });

to

$("td > img").live('click',function(){
                alert("clicked");
        });

Edit: For jQuery 1.9 and later you can do:

$("#board").on('click', 'td > img', function(){
  // handle click
});
like image 142
Funky Dude Avatar answered Sep 28 '22 10:09

Funky Dude