JS中單引號/雙引號以及外部js引入的一些問題

來源:互聯網
上載者:User

標籤:javascript

一、單引號和雙引號的用法的問題

        在JavaScript中可以使用單引號、雙引號,二者也可以混合使用。但是,身為菜鳥的我,卻碰到了一些引號的使用問題。

<body><div style="border:1px solid red; height:150px;width:150px;" onclick="alert("test");"  id="test">This is a test.</div></body>

理論上,點擊這個div會有彈框,但是無論你怎麼點擊,彈框都不出現,不信?點擊查看示範。左思右想,代碼都沒有問題,但是修改了一個小地方,彈框就出來了

<body><div style="border:1px solid red; height:150px;width:150px;" onclick="alert('test');"  id="test">This is a test.</div></body>

點擊查看示範,我覺得很奇怪,於是又改了一個小地方,彈框又沒了

<body><div style="border:1px solid red; height:150px;width:150px;" onclick='alert('test')'  id="test">This is a test.</div></body>

點擊查看示範,我有點暈頭轉向,為了更明白一點,一個小地方的修改,彈框有出現了

<body><div style="border:1px solid red; height:150px;width:150px;" onclick='alert("test")'  id="test">This is a test.</div></body>

點擊查看示範。

    PS:可以把代碼放到編輯器中,查看修改的小地方的字型顏色變化!!!



二、在<head>引入外部js的問題

       在一般的項目中,js、css和HTML都是分開的,一般是通過在<head>中通過對應元素的src屬性引入。我在<head>中引入外部的test.js檔案。

HTML:

<pre name="code" class="javascript"><body><div style="border:1px solid blue; height:150px;width:150px;" onclick="test();"   id="test">This is a test.</div></body>



test.js

window.onload=function(){<pre name="code" class="javascript">function test(){alert("test");}}



點擊div沒有彈窗,效果示範


修改後test.js檔案

function test(){alert("test");}

彈窗出現,效果示範,也可以去掉div的onclick屬性,在js中添加,修改如下:

HTML:

<body><div style="border:1px solid blue; height:150px;width:150px;"   id="test">This is a test.</div></body>

修改的test.js

window.onload=function(){var test = document.getElementById("test");test.onclick = function(){alert("test");}}

效果示範

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.