开关不激活功能

switch not activating function

本文关键字:功能 激活 开关      更新时间:2023-09-26

当检测到不同的操作系统时,这应该显示不同的东西,但它什么也不显示。我知道该函数有效,因为如果我在没有开关的情况下调用该函数,它会显示。此外,崇高的文本链接只是一个测试。这是我的代码:

<script type="text/javascript">
            function Mac(){
                document.write("<a href='"http:'/'/www.sublimetext.com'/'">Sublime Text<'/a>");
                document.write("This is the Mac instructions";)
            }
        </script>
        <script type="text/javascript">
            function Windows(){
                document.write("<a href='"http:'/'/www.sublimetext.com'/'">Sublime Text<'/a>");
                document.write("This is the Windows instructions";)
            }
        </script>
    </div>
    <div class="text-center">
        <h1>Lesson 1: Prerequisites</h1>
            <script>
                switch(OSName) {
                    case "Mac":
                        Mac()
                        break;
                    default:
                        Windows()
                }
            </script>
    </div>

我从上面得到OSName:

            <script>
            var OSName="Unknown OS";
            if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
            if (navigator.appVersion.indexOf("Mac")!=-1) OSName="Mac";
            if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
            if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
            </script>

我知道这有效,因为我可以用以下方法显示它:

document.write('Your operating system has been determined as '+OSName +'.');

您的Mac()Windows()函数中有拼写错误。而不是

document.write("This is the Mac instructions";)
document.write("This is the Windows instructions";)

document.write("This is the Mac instructions");
document.write("This is the Windows instructions");

请注意,您不应该将每个函数放在不同的<script>标签中。这是工作示例:http://jsfiddle.net/kyqLjqb3/7/

我不确定这是否可能是问题所在,但也许在您的 Mac 和 Windows 函数中,您应该替换以下代码:

document.write("This is the Mac instructions";)    
document.write("This is the Windows instructions";)

document.write("This is the Mac instructions");    
document.write("This is the Windows instructions");

分号可能是问题所在,document.write 可能认为您要在右括号之前结束语句

"document.write"通常用于编写JavaScript时的测试目的。但是document.write有问题并且已经过时了。为了在当今进行适当的测试,您应该使用"console.log"。然后,您的代码应如下所示:

console.log("This is the Mac instructions");    
console.log("This is the Windows instructions");

请记住,要查看输出,您需要在浏览器"开发人员工具"中打开控制台。

如果要适当地使用字符串在 html 中打印,则可能需要使用回车键或将字符串直接附加到 html 元素。我希望这在某种程度上有所帮助。