我有下面的函数,当3个变量都不为null时,它工作得很好,但是,如何修改它,以便当其中一个变量(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>发布于 2012-12-05 04:14:20
让我向您介绍条件语句:
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。
发布于 2012-12-05 04:14:36
试试这个:
<!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>发布于 2012-12-05 04:15:30
您需要测试每个变量:
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不为空/ '',则'<div>T. '+ tel +'</div>\n'否则为null
演示:http://jsfiddle.net/gHdy8/
https://stackoverflow.com/questions/13711053
复制相似问题