繁体   English   中英

Visual Studio 2015 Community Edition中的onclick按钮未调用JavaScript函数

[英]JavaScript function not called at onclick button in Visual Studio 2015 Community Edition

我正在学习JavaScript和CSS,并在Visual Studio 2015社区版中进行了一个测试项目。 我遇到的问题是,使用Visual Studio 2015社区版时未调用功能changeTitleCSSStyle。 在在线编辑器https://js.do/上以及在Google Chrome浏览器中,函数调用可以正常运行。 我的代码:

index.htm的

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="css/default.css">
    <title>JavaScript and HTML</title>
    <meta charset="utf-8" />
    <script>
        function changeTitleCSSStyle() {
            alert("Aanroep");
            var title = document.querySelector("#mainTitle");
            title.style.color = 'black';
            title.style.backgroundColor = "yellow";
            title.style.border = "5px dashed red";
        }
    </script>
</head>
<body>
    <h1 id="mainTitle">My home page</h1>
    <p>This is an example of interactivity between JavaScript and the HTML content of a document.</p>
    <button onclick="javascript: changeTitleCSSStyle();">Change style</button>
</body>
</html>

default.css

h1 {
    color: red;
    background-color: lightGreen;
    border: 12px solid violet;
    padding: 5px;
    border-radius: 15px;
    text-align: center;
}

p, h1 {
    font-family: cursive;
}

p, img, button {
    margin-left: 50px;
}

你可以试试

<button onclick="changeTitleCSSStyle();">Change style</button>

不知道为什么在使用VS时它不起作用。 也许由于某些原因不支持嵌入式点击事件。

如果您尝试像这样在脚本本身中设置事件,则可能会起作用:

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript and HTML</title>
<meta charset="utf-8" />
<script>
    function changeTitleCSSStyle() {
        alert("Aanroep");
        var title = document.querySelector("#mainTitle");
        title.style.color = 'black';
        title.style.backgroundColor = "yellow";
        title.style.border = "5px dashed red";
    }

    document.addEventListener("DOMContentLoaded", function(event) {
        var button = document.getElementById('change_style_button')
        button.addEventListener('click', function(){
            changeTitleCSSStyle()
        });
     });

</script>
</head>
<body>
    <h1 id="mainTitle">My home page</h1>
    <p>This is an example of interactivity between JavaScript and the HTML content of a document.</p>
    <button id="change_style_button">Change style</button>
</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM