简体   繁体   中英

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

Not sure if this is possible, my editors highlighting doesn't seem to think so... I'm trying to run the same code over built in functions like previousSibling, nextSibling (I've had other scenarios where looping over different functions would be helpful). Even if there's a built in function I don't know that can remove spaces between nodes for me (please let me know if there is), I would like to know if taking a function as an argument and then calling it with another element to get a value is possible. The previousSibling and nextSibling are able to be called on "input" so why shouldn't this work?

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>

previousSibling and nextSibling are no functions. You use them as plain variables, but they don't exist in your function's scope.

To pass functions, use

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; });
}

However, since previousSibling and nextSibling are properties it would be easier in your case to pass property names, and use bracket notation to access them:

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

Btw, your while -loops with that boolean loop variable were really scary. Either use while(true) { if(…) break; } while(true) { if(…) break; } , or just temp as the condition itself (as in my examples above)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM