Pregunta

I need to disable the click of a cell after the user has clicked on it. Let me explain:
I click on the cell n.3 in the table, and after this should no longer be clickable. You can do this? I make this code for obtain the cell:

var trs = document.getElementsByTagName('td');

for(var i = 0; i < trs.length; i++)
{
trs[i].onclick = clickHandler;
console.log([i]);
}
¿Fue útil?

Solución

Not a javascript programmer, but i'll try to answer:

Your code just initializes the onclick event over all your 'td' elements to use clickHandler.

Every event handler admits an event, which has a reference to the object subject of that event inside. So if you implement clickHandler like this:

// Add event to your clickHandler prototype if not already present
funcion clickHandler(event) {
    // Your existing code
    event = event || window.event; // window.event used in IE<9
    event.target.onclick = null; // event.target is the element clicked (myself!)
}

This way your clickHandler will deactivate the onclick event on the target once called, which seems what you asked for. I've not tried this, but may work or give you the idea.

EDIT: Full example:

<html>
<head>
<title>Test</title>
<script language="javascript">
function clickHandler(event) {
    window.alert("You clicked on an unclicked cell!");
    event = event || window.event;
    event.target.onclick = null;
}

window.onload = function() {
    var trs = document.getElementsByTagName('td');

    for(var i = 0; i < trs.length; i++)
    {
        trs[i].onclick = clickHandler;
    }
}
</script>
</head>
<body>
<h1>Test</h1>
<table>
    <tr>
        <td>asdf</td>
        <td>asdf</td>
        <td>asdf</td>
    </tr>
    <tr>
        <td>asdf</td>
        <td>asdf</td>
        <td>asdf</td>
    </tr>
    <tr>
        <td>asdf</td>
        <td>asdf</td>
        <td>asdf</td>
    </tr>
</table>
</body>
</html>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top