如何将函数作为参数传递给Javascript中的自定义函数

How to pass a function as an argument to a custom function in Javascript

本文关键字:Javascript 自定义函数 参数传递 函数      更新时间:2023-09-26

不确定这是否可能,我的编辑高亮显示似乎不这么认为…我试图运行相同的代码在内置的功能,如previousSibling, nextSibling(我有其他场景,在不同的功能上循环将是有帮助的)。即使有一个内置的函数,我不知道可以为我删除节点之间的空间(请让我知道是否有),我想知道是否将函数作为参数,然后用另一个元素调用它以获得一个值是可能的。previousSibling和nextSibling可以在"输入"时调用,所以为什么不能这样做呢?

spaces.js

window.addEventListener("load", function () {
function removeSpaces (element) {
  function movement (direction) {
    var loop = true;
    while (loop) {
      if (element.direction) {
        var temp = element.direction;
        if ((!temp.id) && (!temp.name) && (!temp.className) && (!temp.value) && (!temp.type) && (!temp.onclick) && (!temp.style)) {
          temp.parentNode.removeChild(temp);
        } else {
          element = temp;
        }
      } else {
        loop = false; // This should only execute if the loop has gotten to either end of the siblings.
      }   
    }
  }
  movement(previousSibling); //These two lines are the problem...
  movement(nextSibling);
}
var input = document.getElementById("input");
removeSpaces(input);
alert(input.nextSibling.id);
});

input.html

<html>
<head>
<script src="spaces.js"></script>
</head>
<body>
<div> Input: </div>
<div> <input id="previousNode"> <input id="input"> <input id="nextNode"> </div>
</body>
</html>

previousSiblingnextSibling为无函数。您可以将它们用作普通变量,但它们不存在于函数的作用域中。

传递函数,使用

function removeSpaces (element) {
  function movement (direction) {
    var temp;
    while (temp = direction(element)) { // call a function
      …
    }
  }
  movement(function(el) { return el.previousSibling; }); // a function expression
  movement(function(el) { return el.nextSibling; });
}

但是,由于previousSiblingnextSibling是属性,因此在您的情况下传递属性名称并使用括号符号来访问它们会更容易:

function removeSpaces (element) {
  function movement (direction) {
    var temp;
    while (temp = element[direction]) { // access a dynamic property
      …
    }
  }
  movement("previousSibling"); // a string
  movement("nextSibling");
}

顺便说一句,你的while循环和布尔变量loop真的很可怕。要么使用while(true) { if(…) break; },要么只使用temp作为条件本身(就像我上面的例子一样)