简体   繁体   English

如何使用JavaScript在HTML元素的两个ID之间切换?

[英]How do I toggle between two IDs of a HTML element with javascript?

<div id = 'ONE' onclick = "change to id TWO" >One</div>

What I want is that every time I click that div it'll toggle between ID ONE and ID TWO, if it's on ID TWO and I click it, it switches to ID ONE and vice versa. 我想要的是,每当我单击该div它将在ID ONE和ID TWO之间切换,如果它位于ID TWO上,并且单击它,它将切换到ID ONE,反之亦然。 How can I do that? 我怎样才能做到这一点?

This is most easily accomplished with jQuery. 使用jQuery最容易实现。

First thing that comes to my mind is setting a click counter to 0. If it's even, we will change the id to red , if it's odd, we change the id to blue . 我想到的第一件事是将点击计数器设置为0。如果是偶数,我们将id更改为red ;如果是奇数,则将id更改为blue

 var clickCount = 0; $("div").on("click", function() { clickCount++; $("div").attr("id", clickCount % 2 === 0 ? "blue" : "red"); }); 
 #red { color: red; } #blue { color: blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>This is a div</div> 

Here is the native JavaScript equivalent. 这是本机JavaScript的等价物。

 var div = document.getElementById("my-div"); var clickCount = 0; div.addEventListener("click", function() { clickCount++; div.setAttribute("id", clickCount % 2 === 0 ? "blue" : "red"); }); 
 #red { color: red; } #blue { color: blue; } 
 <div id="my-div">This is a div</div> 

I found the solution: 我找到了解决方案:

function changediv() {
    if (document.getElementById("one")) {
        document.getElementById("one").id = "two";
    } else {
        document.getElementById("two").id = "one";
    }
}

Then on your div 然后在你的div

<div id = "one" onclick = "changediv()" >Your stuff</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM