2010-08-10 105 views
9

我的意思是,可以在HTML中使用聲明和初始化的變量/數組,可以在<script> -tags之外使用嗎? FX。可以在純HTML中使用JavaScript變量嗎?

<script type="text/javascript"> 
var foo = array('placeholder1', 'placeholder2'); 
</script> 

<body> 
<p><!--access the variable here-->foo[0]</p> 
</body> 

在這種情況下如何訪問變量/數組?像這樣:

<p><script type="text/javascript">document.print(foo[0])</script></p> 

?? ??

回答

15

兩種方法可以做到這一點。這是最好的一個:

<script type="text/javascript"> 
// make sure to do this onLoad, for example jQuery's $() 
var foo = array('placeholder1', 'placeholder2'); 
document.getElementById("fooHolder").innerHTML = foo.toString(); 
</script> 
... 
<p id="fooHolder"></p> 

或者你可以做這種方式(其中,馬塞爾指出,不XHTML工作,真的不應該還是使用):

<p><script type="text/javascript">document.write(foo)</script></p> 
+0

'document.write'在XHTML中不起作用:http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite – 2010-08-10 19:10:24

+0

這是設置HTML標記以包含JavaScript變量的一個很好的例子內容。但它不允許你在HTML中指定一個自動返回JavaScript變量內容的JavaScript變量。正確的答案是所問的問題不能完成,但這是一種替代方法。 – 2016-08-25 00:37:53

3

你可以做這樣的事情:

<script> 
    var str = 'hello there'; 
    document.getElementById('para').innerHTML = str; 
</script> 

其中元素具有指定ID:

<p id="para"></p> 
0

這是您在頁面其他地方訪問它的唯一直接方式。通過打開另一個腳本標籤並打印它。

您還可以使用諸如innerHTML之類的方法將值放在某處。

0

我不認爲你可以從html訪問JavaScript,但你可以通過javascript設置一個dom對象的innerhtml,所以你可能想要走相反的路。首先谷歌搜索我發現,所以我不能承諾它的好,但它有一個快速樣本。

http://www.tizag.com/javascriptT/javascript-innerHTML.php

3

你根本無法訪問腳本標籤的JavaScript變量之外,這是因爲,

  1. HTML不承認任何變量,它只是呈現支持的HTML元素
  2. 變量用於存儲臨時變量,即動態數據,如果你想要更動態的東西,那麼你可以使用PHP。
1

不必要地冗長,但使用標準的DOM方法。

<script> 
    window.onload = function(){ 
     // you do not need to initialize like this, but I like to 
     var bar1 = new String('placeholder1'); 
     var bar2 = new String('placeholder2'); 
     var foo = new Array(); 

     // populate the Array with our Strings 
     foo.push(bar1); 
     foo.push(bar2); 

     // create an array containing all the p tags on the page 
     // (which is this case is only one, would be better to assign an id) 
     pArray = document.getElementsByTagName('p'); 

     // create a text node in the document, this is the proper DOM method 
     bar1TextNode = document.createTextNode(foo[0].toString()); 

     // append our new text node to the element in question 
     pArray[0].appendChild(bar1TextNode); 
    }; 
</script> 

<body> 
    <p></p> 
</body> 
0

你甚至可以爲你AngularJS表達。

<html> 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 

    <script> 
     var app = angular.module('myApp', []); 
     app.controller('myCtrl', function($scope) { 
      $scope.framework= "AngularJS"; 
     }); 
    </script> 

    <body> 

     <div ng-app="myApp" ng-controller="myCtrl"> 
      <p>I want to use variables directly in HTML using: {{ framework }}</p> 
     </div> 

    </body> 
</html> 

上面的代碼會打印出「我想在HTML中使用直接使用變量:AngularJS」。你可以用括號寫AngularJS表達。例如:{{表達式}}。

相關問題