0

我在下面有以下函数,当所有 3 个变量都不为空时它工作得很好,但是,如何修改它以便当任一变量(电话、传真、单元格)为空时,包含空变量的行不会得到书面?

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>
4

3 回答 3

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()通常被认为是一个坏主意。你可以在这里阅读更多关于它的信息。

于 2012-12-04T20:14:19.530 回答
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>
于 2012-12-04T20:14:35.777 回答
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''

演示:http: //jsfiddle.net/gHdy8/

于 2012-12-04T20:15:30.213 回答