我正在使用div标签制作一个盒子。用户输入将从提示框中获取,并将显示在固定尺寸的div标签中。如果没有给出输入,则根本不会显示div。
但是,当我没有在提示框中输入任何内容时,即使我已指定else
条件,其可见性设置为隐藏,仍会显示空div。
我认为该程序未输入else
语句的if
条件,无法将div的可见性设置为隐藏。
JavaScript的:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script> css//the js file..
var person1;
function getdata()
{
person1=prompt("Please enter your data 1","Sample 1",max="5");
}
function displayResult()
{
var table1=document.getElementById("table1");
table1.innerHTML=person1;
if(person1.value!="")
{
$("#table1").css({"border-color": "#000000",
"border-width":"1px",
"border-style":"solid",
"visibility" : "visible",
//"position" :"fixed",
//"resize":"both",
"overflow":"auto",
"width":"60px",
//"maxlength":"10",
"height": "80px",
"top": "30px",
"left" : "80px"});
}
else
{
alert("hello");
("#table1").css({"border-color": "#000000",
"border-width":"0px",
"border-style":"solid",
"visibility" : 'hidden',
//"position" :"fixed",
"resize":"both",
"overflow":"auto",
"width" :"60px",
"height" : "80px",
"top": "30px",
"left" : "80px"});
}
}
HTML:
<body>
<form>
<div id="table1" width="1%" height="10%" style="visibility:hidden"></div>
</form>
<button type="button" id="button" onclick="getdata()">Insert data</button>
</body>
这里是jsfiddle
答案 0 :(得分:1)
这是对正确处理空输入的代码的修改。您为“不可见”div指定了宽度和高度,因此在这种情况下存在“不可见空间”。根据需要修改CSS定义。
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="PATH-TO-jQuery"></script>
<script type="text/javascript">
$(function() {
$("#table1").css({"visibility":"hidden", "width":"1%", "heigth":"10%"});
$("#testButton").click(function() {
displayResult();
});
});
var person1;
function getdata()
{
person1=prompt("Please enter your data 1","Sample 1",max="5");
}
function displayResult()
{
$("#table1").text(person1);
if(person1.length)
{
$("#table1").css({"border-color": "#000000",
"border-width":"1px",
"border-style":"solid",
"visibility" : "visible",
//"position" :"fixed",
//"resize":"both",
"overflow":"auto",
"width":"60px",
//"maxlength":"10",
"height": "80px"//,
// "top": top1, // undefined
// "left" : left1 // undefined
});
}
else
{
alert("hello");
("#table1").css({"border-color": "#000000",
"border-width":"0px",
"border-style":"solid",
"visibility" : 'hidden',
//"position" :"fixed",
"resize":"both",
"overflow":"auto",
"width" :"60px",
"height" : "80px",
"top": "30px",
"left" : "80px"});
}
}
</script>
<style type="text/css">
</style>
</head>
<body>
<button id="testButton">displayResult</button>
<form>
<div id="table1"></div>
</form>
<button type="button" id="button" onclick="getdata()">Insert data</button>
</body>
</html>
答案 1 :(得分:0)
只需替换它:
if(person1.value!="")
有了这个:
if(person1 != "")
然后再试一次......
答案 2 :(得分:0)
您需要的测试是:
(person1 != null && person1 != "")
如果用户点击提示框中的取消按钮,则person1将为null,否则为字符串。
如果person1为null,则尝试访问person1.value将产生运行时错误
当person1是字符串person1.value将始终为null,因为它没有这样的属性。在这种情况下:
(person1.value != "")
相当于:
(null != "")
总是如此。