DIV,JS如何实现“加减号”“显示隐藏”效果

JavaScript06

DIV,JS如何实现“加减号”“显示隐藏”效果,第1张

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html charset=utf-8" />

<title>无标题文档</title>

<style type="text/css">

<!--

#box {

height: 130px

width: 310px

border: 1px solid #CECECE

}

#box p {

width: 260px

float: right

margin-top: 20px

margin-right: 0px

margin-bottom: 0px

margin-left: 0px

}

body {

font-size: 12px

margin: 0px

padding: 0px

}

#box .p1 {

font-size: 16px

}

#box .p2 {

color: #999

display: none

}

#box {

position: relative

}

#box a {

display: block

height: 18px

width: 18px

font-size: 18px

text-align: center

line-height: 18px

font-weight: bold

color: #063

border: 1px solid #000

position: absolute

left: 20px

top: 22px

cursor:pointer

}

-->

</style>

</head>

<body>

    <div id="box">

      <p class="p1">How do Lorem ament, consetetur adipiscing elit?</p>

        <p class="p2">Lorem ipsum dolorm upsut Lorem ipsum dolorm upsut Loren ipsum dolorm upsut Lorem ipsum.</p>

        <a>+</a>

    </div>

</body>

</html>

<script language="javascript">

var a = document.getElementsByTagName('a')[0]

var p2 = document.getElementsByTagName('p')[1]

var temp = 0

a.onclick = function()

{

temp++

if (temp%2==0)

{

this.innerHTML = '+'

p2.style.display = 'none'

}

else

{

this.innerHTML = '-'

p2.style.display = 'block'

}

}

</script>

getnumber[i]是onclick函数外面的变量,进来函数就没了,改成this即可。下面是我做了修改的代码:

function clicknumber(){

var getnumber=document.getElementById("test").getElementsByTagName("ul")[0].getElementsByTagName("li")

for( var i=0i<getnumber.lengthi++){

getnumber[i].onclick = function(){

var strtonu = parseInt(this.innerHTML.trim())-1 //这里改了this,数字直接做减一处理,再判断

if(strtonu>0){

this.innerHTML=String(strtonu) //这里改了this

}else{//strtonum为0即隐藏,你原来的代码还会显示0

this.style.display="none" //这里改了this

}

}

}

}