简体   繁体   中英

Hide and Show Divs without using Jquery

I would like to ask if it is possible to modify my code to achieve the same goal it currently does WITHOUT using jquery. I am embedding this code into sharepoint, and our company makes it complicated to levarage jquery in it. Here is the code...

<html>
<head>
<style>
a,img { border: none; }
.comb {display: none;}
</style>
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">     </script>

</head>
<body>


<map name="FPMap0" id="FPMap0">
<area item="first" href="#" shape="polygon" coords="347, 79, 349, 201, 449, 248, 540, 204, 541, 82, 448, 34" />
<area item="second" href="#" shape="polygon" coords="560, 81, 562, 206, 660, 255, 756, 208, 758, 81, 659, 31" />
</map>

<img width="1000" height="667" src="main.png" usemap="#FPMap0" alt=""/>​

<div class="comb" id="first">t1</div>

<div class="comb" id="second">t2</div>


<script>
$('area').on('click',function() {
$('.comb').hide();
$('#' + $(this).attr('item')).show();
});
</script>
</body>
</html>

I have given a detailed step by step, this should work just like the current source code you have but without the use of jQuery.

function toggle(){
    //Get all elements with the class comb
    var comb=document.getElementsByClassName('comb');
    //Loop through all elements
    for(var i=0; i<comb.length; i++){
        //Hide all elements
        comb[i].style.display='none';
    }
    // this = the element used to trigger/fire the function
    // getAttribute("item") = item="something"
    //Display element by ID 
    document.getElementById(this.getAttribute("item")).style.display='block';
}
// Run when Page is ready
window.onload=function(){
    //Get all area elements
    var area=document.getElementsByTagName('area');
    for(var i=0; i<area.length; i++){
        //Set event Listener
        area[i].addEventListener('click',toggle,false);
    }
}

If you have any questions, please leave a comment below and I will get back to you as soon as possible.

I hope this helps. Happy coding!

var areas = document.getElementsByTagName('area');

for(var i = 0; i < areas.length; i++){
    areas[i].onclick = function(){
        var combs = document.getElementsByClassName('comb');
        combs[i].style.display = 'none';
        var item = this.getAttribute('item');
        document.getElementById(item).style.display = 'block';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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