views:

177

answers:

2

I am new to javascript and have written a piece of code (pasted below). I am trying to build a little game of Battleship. Think of that game with a grid where you place your ships and start clicking on opponents grid blindly if it will hit any of the opponents ships. Problem is I need to get a function called with the ID of the DIV to be passed as a parameter. When the DIV is programmatically created like below, what will work. This? : --///<.DIV id='whatever' onclick='javascript:function(this.ID)' /> .. I saw sth like that somewhere .. this inside html :S

the js code is: (there are two grids, represented by the parameter - who - ... size of grid is also parametric)

function createPlayGround(rows, who)
{
    $('#container').hide();
        var grid = document.getElementById("Grid" + who);
        var sqnum = rows * rows;

        var innercode = '<table cellpadding="0" cellspacing="0" border="0">';
             innercode += '<tr>';
                for (i=1;i<=sqnum;i++)
                {
                    var rowno = Math.ceil(i / rows);
                    var colno = Math.ceil(i - ((rowno-1)*rows));
                    innercode += '<td><div id="' + who + '-' + i +'" class="GridBox'+ who +'" onmouseover="javascript:BlinkTarget(' + i + ',' + who +');" onclick="javascript:SelectTarget('+ i + ',' + who +');" >'+ letters[colno - 1] + rowno +'</div></td>';
                        if (i % rows == 0)
                        {
                           innercode += '</tr><tr>';
                        }
                }
            innercode += '</tr></table>';
            grid.innerHTML = innercode;
        $('#container').fadeIn('slow');
}
+7  A: 

It sounds like what you really want is to get the div element that was just clicked on. If you just want to return the div that was clicked on, all you have to do is use "this":

<div id="whatever" onclick="function(this)"></div>

If you're actually more interested in getting the id of the div clicked on, you can do this:

<div id="whatever" onclick="function(this.id)"></div>

However, it sounds like you just want the id so that you can get the div using getElementById, and the first code snippet will help you skip that step.

Daniel Lew
i see .. i actually just tried it and amazed that it works. Thanks!
If this solution worked, you should mark it as accepted.
luiscubal
by clicking the checkbox next to it
Click Upvote
+1  A: 

Instead of creating the inner html from strings you can create it with jQuery and add event listeners like so:

$("<div></div>")
  .click(function(e) {
    selectTarget(i, who);
  })
  .appendTo(container);
Daniel X Moore