如何在函数中创建全局变量

How to make global variable in a function?

本文关键字:创建 全局变量 函数      更新时间:2023-09-26

我有这样的代码(http://jsfiddle.net/tb7E9/1/):

<script>
    function listEvents(json) {
        var feed = json.feed;
        for (var i = 0; i < 3; i++) {
            var entry = json.feed.entry[i];
            var posttitle = entry.title.$t;
            //Style
            if (i == 0) {
                x = "<span style='color:red'>Style 1 </span><p>" + posttitle + "</p>";
                p = "<span style='color:red'>Style 2 </span><h4>" + posttitle + "</h4><p>";
            }
            if (i == 1) {
                y = "<p>" + posttitle + "</p>";
                g = "<h4>" + posttitle + "</h4></p>";
            }
        }
        style1 = x + y; document.write(style1);
        style2 = p + g; document.write(style2);
    }
</script>

第二个脚本:

<script>
    //How to style1 is actived and style2 is disable here?
    document.write("<script src='"http://www.allbloggertricks.com/feeds/posts/default/-/Tutorials?orderby=published&alt=json-in-script&callback=listEvents'"><'/script>");
</script>
我只想显示样式(样式 1(普通文本)

或样式 2(粗体文本)作为 jsfiddle 中的示例)。这意味着如果我选择 style1 进行显示,则 style2 将被禁用。

如何更改第二个脚本中的代码来执行此操作?

这是存档它的正确方法。

function Y (){
  var window.X = *** ;
  console.print(window.X):
  console.print(X):
}
Y():
console.print(window.X):