我在下面有以下功能,当所有3个变量都不为空时它很有效,但是,如何修改它,使得当变量(tel,fax,cell)为null时,包含null变量的行不写?
Current scenario:
T. 123-4567-8910
F. 987-654-3210
C.
-------------------------------
Desired scenario:
T. 123-4567-8910
F. 987-654-3210
-------------------------------
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function test() {
var tel = "123-4567-8910"
var fax = "987-654-3210"
var cell = ""
var html =
'<div>T. '+ tel +'</div>\n' +
'<div>F. '+ fax +'</div>\n' +
'<div>C. '+ cell +'</div>'
document.write(html)
}
</script>
</head>
<body>
<a href="javascript:test()">test</a>
</body>
</html>
答案 0 :(得分:1)
让我向您介绍条件陈述:
var html = '';
if (tel) {
html += '<div>T. '+ tel +'</div>\n';
}
if (fax) {
html += '<div>F. '+ fax +'</div>\n';
}
if (cell) {
html += '<div>C. '+ cell +'</div>\n';
}
document.write(html)
虽然document.write()
通常被认为是个坏主意。您可以阅读更多相关信息here。
答案 1 :(得分:0)
试试这个:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function test() {
var tel = "123-4567-8910";
var fax = "987-654-3210";
var cell = "";
var html = "";
if (tel == "") {
html = html + '<div>T. '+ tel +'</div>\n';
}
if (fax == "") {
html = html + '<div>F. '+ fax +'</div>\n';
}
if (cel == "") {
html = html + '<div>C. '+ cel +'</div>\n';
}
document.append(html);
}
</script>
</head>
<body>
<a href="javascript:test()">test</a>
</body>
</html>
请记住接受正确的答案,并提出任何对您有帮助的答案/评论。
答案 2 :(得分:0)
您需要测试每个变量:
var html =
((tel)?'<div>T. '+ tel +'</div>\n':'') +
((fax)?'<div>F. '+ fax +'</div>\n':'') +
((cell)?'<div>C. '+ cell +'</div>':'') ;
document.write(html);
工作原理:
(tel)?'<div>T. '+ tel +'</div>\n':''
表示:如果tel不为空/ null,则为'<div>T. '+ tel +'</div>\n'
else ''