Отключение элемента абзаца

Я пытаюсь создать простую игру в крестики-нолики, и мне нужно, чтобы мой элемент p был отключен, как только я щелкну по нему. Я могу получить X и 0 случайным образом, но не смог выяснить, отключив элемент P. Заранее спасибо. Если требуется еще что-нибудь, пожалуйста, сообщите мне. Вот мой код:

var xValue = "x";


// function for alternating value of x 
function alternateX() {
  if (xValue === "x") {
    xValue = 0;
  } else {
    xValue = "x"
  }
}

// function to unbind a box
function box1Click() {

  alternateX();

  document.querySelector(".box1").textContent = xValue;
}


function box2Click() {

  alternateX();

  document.querySelector(".box2").textContent = xValue;
}

function box3Click() {

  alternateX();

  document.querySelector(".box3").textContent = xValue;
}

function box4Click() {

  alternateX();

  document.querySelector(".box4").textContent = xValue;
}

function box5Click() {

  alternateX();

  document.querySelector(".box5").textContent = xValue;
}

function box6Click() {

  alternateX();

  document.querySelector(".box6").textContent = xValue;
}

function box7Click() {

  alternateX();

  document.querySelector(".box7").textContent = xValue;
}

function box8Click() {

  alternateX();

  document.querySelector(".box8").textContent = xValue;
}

function box9Click() {

  alternateX();

  document.querySelector(".box9").textContent = xValue;
}
#container {
  margin-left: auto;
  margin-right: auto;
  height: 300px;
  width: 300px;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-row-gap: 0px;
  grid-column-gap: 0px;
  grid-template-areas: "box1 box2 box3" "box4 box5 box6" "box7 box8 box9 ";
}

.box1 {
  grid-area: box1;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-left: 0px;
  border-top: 0px;
  cursor: pointer;
}

.box2 {
  grid-area: box2;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-top: 0px;
  cursor: pointer;
}

.box3 {
  grid-area: box3;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-top: 0px;
  border-right: 0px;
  cursor: pointer;
}

.box4 {
  position: relative;
  margin-top: -18%;
  grid-area: box4;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-left: 0px;
  border-top: 0px;
  cursor: pointer;
}

.box5 {
  margin-top: -18%;
  grid-area: box5;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-top: 0px;
  cursor: pointer;
}

.box6 {
  margin-top: -18%;
  grid-area: box6;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-top: 0px;
  border-right: 0px;
  cursor: pointer;
}

.box7 {
  margin-top: -17%;
  grid-area: box7;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-left: 0px;
  border-top: 0px;
  border-bottom: 0px;
  cursor: pointer;
}

.box8 {
  margin-top: -17%;
  grid-area: box8;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-top: 0px;
  border-bottom: 0px;
  cursor: pointer;
}

.box9 {
  margin-top: -17%;
  grid-area: box9;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-top: 0px;
  border-bottom: 0px;
  border-right: 0px;
  cursor: pointer;
}
<div id = "container">

  <p class = "box1" onclick = "box1Click()"></p>
  <p class = "box2" onclick = "box2Click()"></p>
  <p class = "box3" onclick = "box3Click()"></p>
  <p class = "box4" onclick = "box4Click()"></p>
  <p class = "box5" onclick = "box5Click()"></p>
  <p class = "box6" onclick = "box6Click()"></p>
  <p class = "box7" onclick = "box7Click()"></p>
  <p class = "box8" onclick = "box8Click()"></p>
  <p class = "box9" onclick = "box9Click()"></p>



</div>

Игнорируйте эту часть: «Если что-то еще требуется, сообщите мне». Я не смог опубликовать сообщение из-за меньшего количества информации.

sanchit arora 24.12.2018 11:39

После каждого щелчка по окошку вы можете удалить функцию onClick следующим образом: document.querySelector(".box2").onClick = null

Thomas Lombart 24.12.2018 11:46
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
2
134
4
Перейти к ответу Данный вопрос помечен как решенный

Ответы 4

Атрибут disabled не применяется к элементу p.

Посмотри на этот https://www.w3schools.com/tags/att_disabled.asp

Я проверил это и думаю, мне лучше использовать тег ввода, а не p.

sanchit arora 24.12.2018 11:49

Вы можете изменить обработчики кликов так, чтобы они ничего не делали (фактически отключив поля), если на поле щелкнули раньше:

function box1Click() {
    const val = document.querySelector(".box1").textContent;
    if (val !== '') return;
    alternateX();
    document.querySelector(".box1").textContent = xValue;
}

Большое спасибо за Вашу помощь.

sanchit arora 24.12.2018 11:55

Без проблем. Отметьте ответ как принятый, если вы считаете это дело закрытым

ack_inc 24.12.2018 11:57
Ответ принят как подходящий

Добавьте document.querySelector(".box1").style.pointerEvents = "none";, чтобы отключить щелчок

var xValue = "x";


// function for alternating value of x 
function alternateX() {
  if (xValue === "x") {
    xValue = 0;
  } else {
    xValue = "x"
  }
}

// function to unbind a box
function box1Click() {

  alternateX();

  document.querySelector(".box1").textContent = xValue;
  document.querySelector(".box1").style.pointerEvents  = "none";
}


function box2Click() {

  alternateX();

  document.querySelector(".box2").textContent = xValue;
  document.querySelector(".box2").style.pointerEvents  = "none";
}

function box3Click() {

  alternateX();

  document.querySelector(".box3").textContent = xValue;
  document.querySelector(".box3").style.pointerEvents  = "none";
}

function box4Click() {

  alternateX();

  document.querySelector(".box4").textContent = xValue;
  document.querySelector(".box4").style.pointerEvents  = "none";
}

function box5Click() {

  alternateX();

  document.querySelector(".box5").textContent = xValue;
  document.querySelector(".box5").style.pointerEvents  = "none";
}

function box6Click() {

  alternateX();

  document.querySelector(".box6").textContent = xValue;
  document.querySelector(".box6").style.pointerEvents  = "none";
}

function box7Click() {

  alternateX();

  document.querySelector(".box7").textContent = xValue;
  document.querySelector(".box7").style.pointerEvents  = "none";
}

function box8Click() {

  alternateX();

  document.querySelector(".box8").textContent = xValue;
  document.querySelector(".box8").style.pointerEvents  = "none";
}

function box9Click() {

  alternateX();

  document.querySelector(".box9").textContent = xValue;
  document.querySelector(".box9").style.pointerEvents  = "none";
}
#container {
  margin-left: auto;
  margin-right: auto;
  height: 300px;
  width: 300px;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-row-gap: 0px;
  grid-column-gap: 0px;
  grid-template-areas: "box1 box2 box3" "box4 box5 box6" "box7 box8 box9 ";
}

.box1 {
  grid-area: box1;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-left: 0px;
  border-top: 0px;
  cursor: pointer;
}

.box2 {
  grid-area: box2;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-top: 0px;
  cursor: pointer;
}

.box3 {
  grid-area: box3;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-top: 0px;
  border-right: 0px;
  cursor: pointer;
}

.box4 {
  position: relative;
  margin-top: -18%;
  grid-area: box4;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-left: 0px;
  border-top: 0px;
  cursor: pointer;
}

.box5 {
  margin-top: -18%;
  grid-area: box5;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-top: 0px;
  cursor: pointer;
}

.box6 {
  margin-top: -18%;
  grid-area: box6;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-top: 0px;
  border-right: 0px;
  cursor: pointer;
}

.box7 {
  margin-top: -17%;
  grid-area: box7;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-left: 0px;
  border-top: 0px;
  border-bottom: 0px;
  cursor: pointer;
}

.box8 {
  margin-top: -17%;
  grid-area: box8;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-top: 0px;
  border-bottom: 0px;
  cursor: pointer;
}

.box9 {
  margin-top: -17%;
  grid-area: box9;
  width: 100px;
  border-style: solid;
  height: 100px;
  border-top: 0px;
  border-bottom: 0px;
  border-right: 0px;
  cursor: pointer;
}
<div id = "container">

  <p class = "box1" onclick = "box1Click()"></p>
  <p class = "box2" onclick = "box2Click()"></p>
  <p class = "box3" onclick = "box3Click()"></p>
  <p class = "box4" onclick = "box4Click()"></p>
  <p class = "box5" onclick = "box5Click()"></p>
  <p class = "box6" onclick = "box6Click()"></p>
  <p class = "box7" onclick = "box7Click()"></p>
  <p class = "box8" onclick = "box8Click()"></p>
  <p class = "box9" onclick = "box9Click()"></p>



</div>

var xValue = "x";


// function for alternating value of x 
function alternateX() {
  if (xValue === "x") {
    xValue = 0;
  } else {
    xValue = "x"
  }
  return xValue;
}

// function to unbind a box
function boxClick(element) {
  if (element.getAttribute("data-is-disable") == true){ return }

  element.setAttribute("data-is-disable", true);
  element.textContent = alternateX();
}

Вам нужно указать CSS, выбрав p[data-is-disable='true']{ }, чтобы отобразить некоторые отключенные стили.

<div id = "container">

  <p class = "box1" onclick = "boxClick(this)"></p>
  <p class = "box2" onclick = "boxClick(this)"></p>
  <p class = "box3" onclick = "boxClick(this)"></p>
  <p class = "box4" onclick = "boxClick(this)"></p>
  <p class = "box5" onclick = "boxClick(this)"></p>
  <p class = "box6" onclick = "boxClick(this)"></p>
  <p class = "box7" onclick = "boxClick(this)"></p>
  <p class = "box8" onclick = "boxClick(this)"></p>
  <p class = "box9" onclick = "boxClick(this)"></p>



</div>

Другие вопросы по теме