私はjavascript(通常はc ++)に非常に慣れていないため、この質問は皆さんにとって非常に基本的なものであると思います.
外部の .js ファイルで定義された変数を取得し、アラートを使用して表示するスクリプトがあります。
.html ファイルのコードは次のようになります。
<html>
<head>
<title></title>
<script>
function addScript(url){
var extScript = document.createElement('script');
extScript.type = 'text/javascript';
extScript.src = url;
extScript.id = 'extScript'
//If there is already a script with the ID 'extScript'
//get rid of it
var headList = document.getElementsByTagName('head');
var scriptList = headList[0].getElementsByTagName('script');
for(var i = 0; i < scriptList.length; i++)
{
if(scriptList[i].id =='extScript')
{
document.getElementsByTagName('head')[0].removeChild(scriptList[i]);
}
}
document.getElementsByTagName('head')[0].appendChild(extScript);
}
function newNewChangeMode()
{
addScript("C:/Users/Suzaku/Documents/Javascript/controller.js");
alert("Neo controllerMode variable is reading " + controllerMode);
}
</script>
</head>
<body>
<a href="javascript:newNewChangeMode()">Get externally defined mode</a>
</body>
</html>
そして、ファイル「controller.js」は次のようになります。
var controllerMode = 1111;
(それでおしまい!)
「外部定義モードを取得」リンクをクリックすると、JavaScript が実行され、アラートが正しく表示されます。「Neo controllerMode variable is reading 1111」と表示されます。
ただし、変数 controllerMode の定義 (controller.js 内) を次のように変更すると、
var controllerMode = 2222;
、保存を押して、ボタンをもう一度クリックしても(更新せずに)、「Neo controllerMode variable is reading 1111」という警告が表示されます。一方、「Neo controllerMode 変数は 2222 を読み取っています」と言う必要があります。
このスクリプトは動的に追加されていないようです。.html を更新しなくても、この変数を変更できる必要があります。
前もって感謝します、
男