为什么不能调用数组中存储的jQuery方法?

时间:2018-08-12 17:07:20

标签: javascript jquery html methods

这些按钮应该在图像上执行showhidetoggle等功能,但是它们无法正常工作。有人告诉我,我正在销毁thisshow等函数中对hide的引用。我该如何解决?

/// <reference path="jquery-3.3.1.js" />

var functionArray = [$('img').show, $('img').hide, $('img').toggle, $('img').fadeIn, $('img').fadeOut, $('img').fadeToggle];
var buttonArray = [$('.show'), $('.hide'), $('.toggle'), $('.fadein'), $('.fadeout'), $('.fadetog')]
var counter = 0

while (counter < buttonArray.length) {
  executer(counter)
  counter++
}

function executer(counter) {
  buttonArray[counter].click(function() {
    functionArray[counter]();
  })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://placehold.it/300x50" />
<br />
<button class="show">Show</button>
<button class="hide">Hide</button>
<button class="toggle">Toggle</button>
<button class="fadein">Fade in</button>
<button class="fadeout">Fade out</button>
<button class="fadetog">Fade toggle</button>

<!-- Script sources in the original code:
<script src="Scripts/jquery-3.3.1.js"></script>
<script src="Scripts/Script1.js"></script>
-->

1 个答案:

答案 0 :(得分:0)

是的,当您将方法与对象分开存储时,上下文会丢失。

由于所有方法的上下文对象都是相同的,因此解决此问题的最简单方法是根本不存储上下文对象,而只存储方法名称。

functionArray将仅包含方法名称作为字符串;然后$("img")[functionArray[counter]]();可以对其进行访问和调用。

扩展此代码段以查看运行中的工作代码:

var functionArray = [
    "show",
    "hide",
    "toggle",
    "fadeIn",
    "fadeOut",
    "fadeToggle"
  ],
  buttonArray = [
    $('.show'),
    $('.hide'),
    $('.toggle'),
    $('.fadein'),
    $('.fadeout'),
    $('.fadetog')
  ],
  counter = 0;

while (counter < buttonArray.length) {
  executer(counter);
  counter++;
}

function executer(counter) {
  buttonArray[counter].click(function() {
    $("img")[functionArray[counter]]();
  })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://placehold.it/300x50" />
<br />
<button class="show">Show</button>
<button class="hide">Hide</button>
<button class="toggle">Toggle</button>
<button class="fadein">Fade in</button>
<button class="fadeout">Fade out</button>
<button class="fadetog">Fade toggle</button>