html 调用 js 脚本发现直接在 js 中写的语句, 使用:
- <script src="scripts/main.js">
- </script>
main.js:
- var myHeading = document.querySelector('h1'); // 获取 header 元素
- myHeading.title = 'hello world!';
- myHeading.textContent = 'hello world!';
- var iceCream = 'chocolate';
- if (iceCream === 'chocolate') {
- alert('Yay, I love chocolate ice Cream');
- } else {
- alert('Awww, but chocolate is my favorite');
- }
包含在 html 中并不会执行, 需要在 js 中将代码加入到函数中, 在 html 中告知执行的时间:
- var iceCream = 'chocolate';
- function show() {
- if (iceCream === 'chocolate') {
- alert('Yay, I love chocolate ice Cream');
- } else {
- alert('Awww, but chocolate is my favorite');
- }
- }
html:
- <script type="text/javascript" language="JavaScript">
- window.onload = show();
- </script>
来源: