不使用Jquery隐藏和显示Div

时间:2015-05-20 01:50:17

标签: javascript sharepoint

我想问一下是否可以修改我的代码以实现与目前相同的目标而不使用jquery。我正在将此代码嵌入到sharepoint中,而我们的公司使得jquery中的jquery变得复杂。这是代码......

<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>

2 个答案:

答案 0 :(得分:3)

我已经逐步详细说明,这应该像你现有的源代码一样工作,但不使用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);
    }
}

如果您有任何疑问,请在下面留言,我会尽快给您回复。

我希望这会有所帮助。快乐的编码!

答案 1 :(得分:1)

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';
    }
}