如何从子 aspx 页面更新 JS 文件中的变量

How to update variable in the JS file from a child aspx page

我有一个包含以下代码的 JS 文件。我需要从我的子 aspx 页面更新变量 currentIndex 的值。现在这个 js 引用在父页面上。我想知道该怎么做。应该从 child.aspx 页面传递什么语法才能使 currentIndex 的值随处更新。

(function($, global, undefined) {
  var slides, currentIndex, $container, $fragmentLinks;

  var events = {
...
     prev: function() {
       methods.go(currentIndex-1);
     },
...

您可以公开一个将修改 currentIndex 变量的函数到全局范围。但是这种方法不能很好地扩展,应该被视为不好的做法,因为它可能导致名称冲突和其他缺点。 How to avoid global variables in JavaScript?. So if you need to access parent page from child iframes you should think of better approach like communication through messages 或类似的自定义实现。

目前解决问题的最简单方法是定义一个 setter 函数来更新 currentIndex 变量:

(function($, undefined) {
  var slides, currentIndex, $container, $fragmentLinks;

  window.setCurrentIndex = function(indexValue) {
    currentIndex = indexValue;
  };

  var events = {
...
     prev: function() {
       methods.go(currentIndex-1);
     },
...

如果您想将索引设置为值 3,例如您可以这样做:

window.setCurrentIndex(3);