2017-04-17 14 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をクリックしてください。現在のWebページにリンクが生成されます。どうして?

私はprompt()の文書を参照してください。 prompt()は、ユーザーが入力する文字列を返します。この場合は<a href=javascript:window.close();> Close me </a >です。

私はprompt()の戻り値にコードでhrefを交換しようとした:

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

その後、リンクがエラーでオープンに失敗しました:あなたのファイルがを見つかりませんでした。

誰かがこれを説明できますか?

答えて

4

これはwindow.prompt()またはtarget="new"とは関係ありません。これはjavascript:プロトコルの動作によるものです。 click_meがクリックされた場合、ページのコンテンツが一掃されるとだけ表示テキストresult_content、無content_aheadスパン、これ以上無いclick_meリンク、上記の例では

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

:私は、以下の簡単な例を作りました。

説明:

  1. click_meをクリックすると、ブラウザはjavascript:プロトコルで定義されたJavaScriptプログラムを実行します。
  2. 実行後、文字列が返された場合、ブラウザはそれを「新しいページ」の内容とみなして開きます。とにかく、hrefhttp:またはhttps://と同じロジックです - データをフェッチして新しいページとして表示します。 Firefoxでこの実験を行うことができます。アドレスバーでさえもjavascript://(function(){return 'result_content'})()に変更されています。
  3. 実行後、Stringが返されない場合、「新しいページ」の内容はありません。ブラウザは古いものを表示し続けます。参考のため

、ここjavascript: URL内のJavaScriptの文を記述した古いarticle次のとおりです。

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.

関連する問題