怎樣在網頁中嵌入JS代碼


有四種方法: 

方法1: 在<script>標簽內直接寫代碼

<body>
    <button id="btn">click</button>
    <script>
        document.getElementById("btn").onclick = function(){
            alert("click");
        }
    </script>
</body>

 

方法2: 在使用<script>標簽的src屬性引入外部js文件

// test.js
// document.getElementById("btn").onclick = function(){ alert("hello") };

// test.html
<body>
    <button id="btn">click</button>
    <script src="./test.js">
        因為src引入了外部文件, 因此寫在標簽中的代碼不會執行.
    </script>
</body>

 

方法3: 通過事件屬性

<body>
    <input type="text" onblur="alert(this.value)" />
</body>

 

方法4: 使用URL協議

<body>
    <a href="javascript:alert('hello')">click</a>
</body>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM