通过使用变量调用document.getElementById
时,它返回null值。以下是示例代码:
function savenext(k)
{
qdd=k.id;
var divs = document.getElementsByClassName("qpanel");
for(var i=0;i<divs.length;i++)
{
divs[i].style.display = "none";
}
str = qdd.replace(/SN/g, '');
str='Q'+str;
var d = document.getElementById(str);
d.style.display = "block";
}
&#13;
<div id="main" class="qpanel" id="Q3">
Q3
</div>
<div id="main" class="qpanel" id="Q2">
Q2
</div>
<div id="main" class="qpanel" id="Q6">
Q6
</div>
<input type="button" value="Save and next" id="SN3" onclick="savenext(this)" class="savenext">
<input type="button" value="Save and next" id="SN2" onclick="savenext(this)" class="savenext">
<input type="button" value="Save and next" id="SN6" onclick="savenext(this)" class="savenext">
&#13;
document.getElementById(str)
返回null
答案 0 :(得分:1)
这是可行的解决方案。你给了div两个id
<script >
function savenext(k)
{
qdd=k.id;
divs = document.getElementsByClassName("qpanel");
for(var i=0;i<divs.length;i++)
{
console.log(divs[i])
divs[i].style.display = "none";
}
str = qdd.replace(/SN/g, '');
str='Q'+str;
var d = document.getElementById(str);
console.log(str)
d.style.display = "block";
}
</script>
<div class="qpanel" id="Q3">
Q3
</div>
<div class="qpanel" id="Q2">
Q2
</div>
<div class="qpanel" id="Q6">
Q6
</div>
<input type="button" value="Save and next" id="SN3" onclick="savenext(this)" class="savenext">
<input type="button" value="Save and next" id="SN2" onclick="savenext(this)" class="savenext">
<input type="button" value="Save and next" id="SN6" onclick="savenext(this)" class="savenext">
答案 1 :(得分:0)
需要注意两件事。
*每个项目只应有一个ID。这里每个div都有一个id main和另一个id Q3。 * ID应该是唯一的,但不是必需的。
这是工作代码
<!doctype html>
<html>
<body>
<div class="qpanel" id="Q3">
Q3
</div>
<div class="qpanel" id="Q2">
Q2
</div>
<div class="qpanel" id="Q6">
Q6
</div>
<input type="button" value="Save and next" id="SN3" onclick="savenext(this)" class="savenext">
<input type="button" value="Save and next" id="SN2" onclick="savenext(this)" class="savenext">
<input type="button" value="Save and next" id="SN6" onclick="savenext(this)" class="savenext">
<script>
function savenext(k)
{
qdd=k.id;
var divs = document.getElementsByClassName("qpanel");
for(var i=0;i<divs.length;i++)
{
divs[i].style.display = "none";
}
str = qdd.replace(/SN/g, '');
str='Q'+str;
var d = document.getElementById(str);
d.style.display = "block";
}
</script>
</body>
</html>