2010-08-10 110 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表达。例如:{{表达式}}。

相关问题