How to disable onclick in JavaScript? - Stack Overflow

I have been trying to do something like this.I have a working code, (this is just example), when I cli

I have been trying to do something like this.

I have a working code, (this is just example), when I click on the button the game starts.

In this example I have a loop, that if condition is true, I want to disable the option to click on the button.

I have seen that this el.disabled = true; / e.disabled = true; / td.disabled = true; (Is it possible to disable onclick without altering its function?) should do the job, but this doesn't work for me. Why is that? Or maybe there is another way to do that? (this is not the whole code, only the important parts)

<!DOCTYPE html>
<html>
<head></head>
<body>
  <script type="text/javascript">
    function startgame() {
      var ChessTable;
      var counter = 0;
      var center = document.createElement('center');
      ChessTable = document.createElement('table');

      for (var i = 0; i < 8; i++) {
        var tr = document.createElement('tr');
        for (var j = 0; j < 8; j++) {
          var td = document.createElement('td');
          td.setAttribute('id', counter)
          td.addEventListener('click', s)
        }
        ChessTable.appendChild(tr);
      }
      center.appendChild(ChessTable);
      ChessTable.setAttribute('cellspacing', '0');
      ChessTable.setAttribute('width', '270px');
      document.body.appendChild(center);
    }

    var counterforplayer = 0;

    function s(e) {
      event.target.style.backgroundColor = "green";

      if (counterforplayer >= 5) {
        alert("you cannot play anymore")
        e.disabled = true;
        counterforplayer++;
      }
    }
    }
  </script>
  <button onclick="startgame()">Click me to start a new game</button>
  <div id="container">
    <div id="ph1">
    </div>
  </div>
</body>
</html>

I have been trying to do something like this.

I have a working code, (this is just example), when I click on the button the game starts.

In this example I have a loop, that if condition is true, I want to disable the option to click on the button.

I have seen that this el.disabled = true; / e.disabled = true; / td.disabled = true; (Is it possible to disable onclick without altering its function?) should do the job, but this doesn't work for me. Why is that? Or maybe there is another way to do that? (this is not the whole code, only the important parts)

<!DOCTYPE html>
<html>
<head></head>
<body>
  <script type="text/javascript">
    function startgame() {
      var ChessTable;
      var counter = 0;
      var center = document.createElement('center');
      ChessTable = document.createElement('table');

      for (var i = 0; i < 8; i++) {
        var tr = document.createElement('tr');
        for (var j = 0; j < 8; j++) {
          var td = document.createElement('td');
          td.setAttribute('id', counter)
          td.addEventListener('click', s)
        }
        ChessTable.appendChild(tr);
      }
      center.appendChild(ChessTable);
      ChessTable.setAttribute('cellspacing', '0');
      ChessTable.setAttribute('width', '270px');
      document.body.appendChild(center);
    }

    var counterforplayer = 0;

    function s(e) {
      event.target.style.backgroundColor = "green";

      if (counterforplayer >= 5) {
        alert("you cannot play anymore")
        e.disabled = true;
        counterforplayer++;
      }
    }
    }
  </script>
  <button onclick="startgame()">Click me to start a new game</button>
  <div id="container">
    <div id="ph1">
    </div>
  </div>
</body>
</html>

Share Improve this question edited Jan 14, 2022 at 1:59 ggorlen 58k8 gold badges114 silver badges157 bronze badges asked Jan 14, 2022 at 1:56 MaROMMaROM 951 gold badge1 silver badge6 bronze badges 4
  • so check if what you clicked is disabled inside of the function. If it is, exit – epascarello Commented Jan 14, 2022 at 1:58
  • 1 Nitpick: Please learn to use camel case and variable names that make sense. – epascarello Commented Jan 14, 2022 at 1:59
  • event.target should be e.target – Barmar Commented Jan 14, 2022 at 2:02
  • e.disabled doesn't make sense. e is an Event object, not a DOM element. – Barmar Commented Jan 14, 2022 at 2:03
Add a ment  | 

4 Answers 4

Reset to default 1

You should be setting disabled on the element. You need to check to see if that element is disabled.

function clickedElem (event) {
  const clickedElem = event.target;
  if (clickedElem.disabled) { return false; }
  if (counterForPlayer >= 5) {
    alert("you cannot play anymore")
    clickedElem.disabled = true;
    return false;
  }
  counterForPlayer++;
}

Give the button an ID. Then you can use document.getElementById() to get the button and disable it.

You had a number of other problems:

  • you only incremented counterforplayer inside the if that checks if it's more than 5.
  • You never appended the td to the tr.
  • There's nothing in the td to click on (but maybe your real application makes it visible with CSS).

function startgame() {
  var ChessTable;
  var counter = 0;
  var center = document.createElement('center');
  ChessTable = document.createElement('table');

  for (var i = 0; i < 8; i++) {
    var tr = document.createElement('tr');
    for (var j = 0; j < 8; j++) {
      var td = document.createElement('td');
      td.setAttribute('id', counter)
      td.addEventListener('click', s)
      td.innerText = "X";
      tr.appendChild(td);
    }
    ChessTable.appendChild(tr);
  }
  center.appendChild(ChessTable);
  ChessTable.setAttribute('cellspacing', '0');
  ChessTable.setAttribute('width', '270px');
  document.body.appendChild(center);
}

var counterforplayer = 0;

function s(e) {
  e.target.style.backgroundColor = "green";
  if (counterforplayer >= 5) {
    alert("you cannot play anymore")
    document.getElementById("startbutton").disabled = true;
  }
  counterforplayer++;

}
<!DOCTYPE html>
<html>

<head></head>

<body>
  <button id="startbutton" onclick="startgame()">Click me to start a new game</button>
  <div id="container">
    <div id="ph1">
    </div>
  </div>
</body>

</html>

You can actually wire up multiple functions that respond to an event, using addEventListener. Additionally, you can choose to stop a listener by calling removeEventListener. This also allows you to set that functionality back in again, by just calling addEventListener again, and passing in the original function.

const testButton = document.getElementById("testButton");
const testOutput = document.getElementById("testOutput");

const stopIncrementOutput = () => {
  testButton.removeEventListener("click", incrementOutput);
};

let output = 0;

const incrementOutput = () => {
  testOutput.innerText = output++;
  if (output > 5) {
    stopIncrementOutput();
  }
};

testButton.addEventListener("click", incrementOutput);
<div>
  <button id="testButton">Test button</button>
  <span id="testOutput"></span>
</div>

Whenever you create elements dynamically, you should never add events on every element. You should consider adding an event listener to the parent element and use event bubbling to catch the event. Ideally you should have only one click event listener attached to the body element of a page and get the event target using e.target to implement your specific use cases.

const body = document.querySelector('body').addEventListener('click', (e) => {
  const id = e.target.id;
  
  // handle button 1 click
  if(id === '1') {
    console.log('1 was clicked');
  } 
  
  // handle button 2 click
  if(id === '2') {
    console.log('2 was clicked');
  } 
  
  // handle button 3 click
  if(id === '3') {
    console.log('3 was clicked');
  } 
  
  // handle button 4 click
  // lets say this is the button you dont want to do anything 
  // so dont implement any functionality here
  if(id === '4') {
    
  } 
})
<body>
  <ul>
    <li><button id="1">1</button></li>
    <li><button id="2">2</button></li>
    <li><button id="3">3</button></li>
    <li><button id="4">4</button></li>
  </ul>
</body>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744822095a4595679.html

相关推荐

  • How to disable onclick in JavaScript? - Stack Overflow

    I have been trying to do something like this.I have a working code, (this is just example), when I cli

    2天前
    60

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信