So i'm thinking to changing innerHTML of <p>Click</p>
from content of "Click" into "Clicked" and when being clicked again it changes back again to "Click" (and could be clicked back again to result "Clicked" for endless times).
Can someone give clue? *I appreciate,
This is my fail attempt so far -->
<!DOCTYPE html>
<body>
<p id="event_01">Click</p>
<script>
let goo = document.querySelector("#event_01");
let clickOnce = function() {goo.innerHTML = "Clicked"};
let clickBack = function(){
goo.innerHTML = "Click"};
if(goo.textContent == "Click") {
goo.addEventListener("click", clickOnce);
} else if (goo.textContent == "Clicked") {
goo.addEventListener("click", clickBack);
}
</script>
</body>
答案 0 :(得分:1)
您应将条件放在点击处理程序内,而不是外部。脚本标记之间的内容仅执行一次。当代码运行时(在页面加载时),goo的内容为Click,因此只有将内容设置为“ clicked”的侦听器才会附加到该元素。相反,您应该执行以下操作:
let goo = document.querySelector("#event_01");
let onClick = function() {
if(goo.textContent == "Click"){
goo.innerHTML = "Clicked";
} else {
goo.innerHTML = "Click";
}
};
goo.addEventListener("click", clickOnce);
答案 1 :(得分:0)
您只需要检查.innerHTML
中<p></p>
的值,将其与当前.innerHTML进行比较并相应地进行更改
<!DOCTYPE html>
<body>
<p id="event_01" onClick="myFunction()">Click</p>
<script>
function myFunction() {
var x = document.getElementById("event_01");
if (x.innerHTML === "Click") {
x.innerHTML = "Clicked";
} else {
x.innerHTML = "Click";
}
}
</script>
</body>
答案 2 :(得分:0)
您只需要一个侦听器,并从头开始即可:
let goo = document.querySelector("#event_01");
goo.addEventListener("click", clickListener);
let clickListener = function() {
if (goo.innerHTML == "<p>Click</p>")
goo.innerHTML = "<p>Clicked</p>";
else
goo.innerHTML = "<p>Click</p>";
}
答案 3 :(得分:0)
这很简单。您添加了很多代码。 首先,当单击p时,将click事件分配给clickOnce,但在clickOnce中 返回,您永远不会分配clickBack。
这里是有关您要执行的操作的示例。
let goo = document.querySelector("#event_01");
let clickMe = function() {
if(goo.textContent == "Click")
{
goo.innerHTML = "Clicked";
}
else
{
goo.innerHTML = "Click";
}
}
goo.addEventListener("click", clickMe);
<p id="event_01">Click</p>
答案 4 :(得分:0)
如果您不想使用函数或变量,则可以使用e.target.textContent
<!DOCTYPE html>
<body>
<p id="event_01">Click</p>
<script>
document.querySelector("#event_01").addEventListener('click', (e) => {
if (e.target.textContent === 'Click') {
e.target.textContent = 'Clicked'
} else if (e.target.textContent === 'Clicked') {
e.target.textContent = 'Click'
}
})
</script>
</body>