如何在将变量添加到数组中时将变量传递给函数

时间:2017-08-23 11:02:16

标签: javascript jquery

每次单击th元素时,带有变量的函数(单击的th元素的文本)都存储在数组中。 但是,不是值(1,2或3等),而是存储变量的名称(“列”)。

如何存储该值而不是变量名?

在下面的示例中,您将看到在控制台中,每次单击th元素时都会存储变量名“column”。

var recordedFunctions = [];
$(document).on("click", "th", function() {
  var column = this.innerHTML;
  recordedFunctions.push(function() {sel(column)});
  console.log(recordedFunctions.toString());
  alert(column);
});

function runRecordedActions() {
  console.log(recordedFunctions.toString());
  for (i = 0; i < recordedFunctions.length; i++) {
    recordedFunctions[i]();
  }
}

function sel(v) {
  alert(v);
}
table th {
  height: 25px;
  width: 30px;
  border: 1px solid #757575;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>1</th>
      <th>2</th>
      <th>3</th>
      <th>4</th>
      <th>5</th>
      <th>6</th>
      <th>7</th>
      <th>8</th>
      <th>9</th>
    </tr>
  </thead>
</table>
<br>

<button type="button" onClick="runRecordedActions()">RUN</button>

2 个答案:

答案 0 :(得分:0)

您还需要更改循环和功能。我添加了一个test()并将其推入一个数组中。 这是工作代码:

var recordedFunctions = [];
function test(column) {
    return column;
}
$(document).on("click", "th", function() {
  var column = this.innerHTML;
  recordedFunctions.push(test(column));

  alert(recordedFunctions);
  console.log(recordedFunctions.toString());
  alert(column);
});

function runRecordedActions() {

  for (var key in recordedFunctions) {

    console.log(recordedFunctions[key]());
  }
}

function sel(v) {
  alert(v);
}

答案 1 :(得分:0)

奇怪的是,在stackoverflow片段中,无法获取值存储 recordedFunctions数组,我们可以在fiddler中获取值。检查下面的代码段以及fiddler,它会在触发run按钮时显示所有点击的值。

var recordedFunctions = [];
$(document).on("click", "th", function() {
  var column = this.innerHTML;
  recordedFunctions.push(function() {sel(column)});
  console.log(recordedFunctions[recordedFunctions.length-1].toString());
  alert(column);
});

function runRecordedActions() {
  var output='Values are:';
  for (i = 0; i < recordedFunctions.length; i++) {
    output += (' ' + recordedFunctions[i].toString());
  }
  alert(output);
}

function sel(v) {
  alert(v);
}
table th {
  height: 25px;
  width: 30px;
  border: 1px solid #757575;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>1</th>
      <th>2</th>
      <th>3</th>
      <th>4</th>
      <th>5</th>
      <th>6</th>
      <th>7</th>
      <th>8</th>
      <th>9</th>
    </tr>
  </thead>
</table>
<br>

<button type="button" onClick="runRecordedActions()">RUN</button>