javascript - 交替更改点击值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';
}
解决方案
尝试这个:
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>
推荐阅读
- python - 在 Odoo 视图中以文本形式输出字段
- java - Jackson 的 @JsonProperty 枚举
- amazon-web-services - 为 Lambda 的 AWS Cloudwatch 上的 Paho MQTT 客户端启用日志
- python - 使用 Python 将存储传输作业从一个谷歌云存储区域转移到另一个“无法重写对象”。
- linux - Linux 中 RAW 图像的范围是多少?
- javascript - 单击切换时更改徽标的 css 属性
- angular - 尝试使用 jsPdf 从 html 创建 pdf 时出错
- android - MVP设计模式实践观察
- php - 过滤 laravel 查询时忽略 whereIn
- phpunit - 如何在测试过程中停止 PHPUnit 但仍然获得失败/报告列表?