首页 > 解决方案 > 交替更改点击值javascript

问题描述

我正在尝试将值从 X 交换到 O 或者在单击 div 元素一秒后。一键创建X成功。如何将第二次点击更改为 O 值并进行权衡?

 <div id= "content" style="width: 300px;height: 300px; background:gray;">

 </div>

javascript

const boardArea = document.getElementById("content");
boardArea.addEventListener("click", createDot)

function createDot(event){
// create a span with X after one click and append it to div
const dot = document.createElement("span");
boardArea.appendChild(dot);
dot.innerText="X";

dot.style.color  =  "red";
dot.style.position  =  "absolute";
dot.style.top  =  event.pageY + 'px'; 
dot.style.left  =  event.pageX + 'px'; 

}

标签: javascript

解决方案


尝试这个:

const boardArea = document.getElementById("content");
boardArea.addEventListener("click", createDot)
var currentValue = 'X';
function createDot(event){
  // create a span with X after one click and append it to div
  const dot = document.createElement("span");
  boardArea.appendChild(dot);
  dot.innerText = currentValue;
  currentValue = currentValue === 'X' ? 'O' : 'X';

  dot.style.color  =  "red";
  dot.style.position  =  "absolute";
  dot.style.top  =  event.pageY + 'px'; 
  dot.style.left  =  event.pageX + 'px'; 

}
<div id= "content" style="width: 300px;height: 300px; background:gray;">

 </div>


推荐阅读