在后续函数

时间:2017-07-27 14:14:44

标签: javascript jquery scope global-variables

我有这个代码,它获取所点击的超链接的类,并切换该超链接中特定div的 play 暂停图标。我的Javascript逻辑有问题:



var mediaClicked_class = "";
var previousMediaClicked_class = "";
var pauseIconStatus = null;

// Get class of clicked hyperlink
function mediaClick_class(clicked_class) {
  alert(pauseIconStatus + " : Initial pause Icon status");
  mediaClicked_class = clicked_class; // when i click map hyperlink, pass respective class into variable

  preEmptivePlay(mediaClicked_class, pauseIconStatus);
}

function preEmptivePlay(mediaClicked_class, pauseIconStatus) {
  if (pauseIconStatus == null) { //global var. init.
    //toggle class of currently clicked div.icon
    $("div.icon_" + mediaClicked_class).toggleClass("playicon pauseicon");

    var pauseIconAvailability = $("div.icon_" + mediaClicked_class).hasClass("pauseicon");

    if (pauseIconAvailability) { //true - playing
      pauseIconStatus = 1;; //pause icon is active i.e. song is playing
      previousMediaClicked_class = mediaClicked_class; //store current class to be called later
      alert(pauseIconStatus + " : Current icon status");
    } else { //false - not playing
      pauseIconStatus = 0;; //pause icon is inactive i.e. song is not playing
      previousMediaClicked_class = mediaClicked_class;
      alert(pauseIconStatus + " : Current icon status");

    }
  }
}




问题在于,当我单击超链接时,会调用此函数,第四行每次都会将pauseIconStatus初始化为null,而不是在后续调用中保留可能的值0。

在哪里可以声明此变量初始化为null,然后在后续调用中重新初始化?

1 个答案:

答案 0 :(得分:1)

这里的问题是您将pauseIconStatus作为参数传递给函数preEmptivePlay,这意味着您所做的更改不会在该函数之外看到。

您可以通过添加以下行来明确地看到这一点:

alert(pauseIconStatus + " : After preEmptivePlay pause Icon status");
在您致电mediaClick_class之后立即

进入preEmptivePlay,您会看到pauseIconStatus的值再次为空,因为您在preEmptivePlay内所做的更改永远不会离开功能

如果您更改mediaClick_class,那么请改为:

pauseIconStatus = preEmptivePlay(mediaClicked_class, pauseIconStatus);

并且还更改preEmptivePlay,以便最后一行(已添加)为:

return pauseIconStatus;

您应该会看到pauseIconStatus对第一个点击之后的点击不再null

也可能是,根据调用mediaClick_class的方式,您还需要将return false;添加到单击处理程序的末尾,否则单击超链接将导致页面重新加载,例如如果您的网页名为default.html,链接如下所示:

<a href="default.html" id="myLink"><div id="icon_thing">Text</div></a>

click事件的结束需要看起来像这样:

$("#myLink").on('click', function ()
{
    mediaClick_class('thing');

    return false;
});