2017-04-17 48 views
1

此代碼卡:爲什麼這段代碼會生成一個鏈接?

<a href="javascript:window.prompt('Press OK button to insert this link in the new window ...', '<a href=javascript:window.close();> Close me 
 
      </a >')" target="new"> 
 
     Open "prompt" dialog 
 
</a>

打開Chrome瀏覽器,點擊鏈接Open "prompt" dialog,然後單擊OK。它會在當前網頁中生成一個鏈接。爲什麼?

我看到prompt()的文件。它說prompt()返回一個用戶輸入的字符串,在這種情況下:<a href=javascript:window.close();> Close me </a >

我試圖在代碼替換hrefprompt()返回值:

<a href="'<a href=javascript:window.close();> Close me </a >'" target="new"> 
 
    Open "prompt" dialog 
 
</a>

然後鏈接失敗,出現錯誤打開:您的文件未找到

有人可以解釋這一點嗎?

回答

4

這與window.prompt()target="new"無關,這是由於javascript:協議的行爲。我做了下面一個簡單的例子:

<span>content_ahead</span> 
<a href="javascript:(function(){return 'result_content'})()"> 
    click_me 
</a> 

在上面的例子中,當點擊click_me時,頁面內容都將灰飛煙滅,只顯示文本result_content,沒有content_ahead跨度,無click_me鏈接了。

說明:

  1. 當點擊click_me,瀏覽器將執行由javascript:協議定義JavaScript程序。
  2. 執行後,如果返回一個字符串,瀏覽器會將其作爲「新頁面」的內容並「打開」它。無論如何,這與hrefhttp:https://的邏輯相同 - 獲取數據並將其顯示爲新頁面。您可以在Firefox中進行此實驗,即使地址欄更改爲javascript://(function(){return 'result_content'})()
  3. 執行後,如果沒有字符串返回,則「新頁面」沒有內容。瀏覽器將繼續顯示舊的。

供參考,在這裏是一個古老的article描述javascript: URL中的JavaScript語句:

The JavaScript statement used in a javascript: URL should not return any value. For example, the alert() method doesn't return a value; in other words, it returns undefined. If the statement returns undefined, the browser simply executes it. However, if it returns an explicit value, the browser loads a new page, with the javascript: URL in the Location bar, and the returned value in the body of the page.

相關問題