如何将函数作为参数传递给Javascript中的自定义函数
How to pass a function as an argument to a custom function in Javascript
不确定这是否可能,我的编辑高亮显示似乎不这么认为…我试图运行相同的代码在内置的功能,如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>
previousSibling
和nextSibling
为无函数。您可以将它们用作普通变量,但它们不存在于函数的作用域中。
传递函数,使用
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; });
}
但是,由于previousSibling
和nextSibling
是属性,因此在您的情况下传递属性名称并使用括号符号来访问它们会更容易:
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
作为条件本身(就像我上面的例子一样)
相关文章:
- 用于检查数组中是否存在元素的javascript自定义方法
- 使用没有插件的javascript自定义滚动条
- ArcGIS JavaScript自定义徽标
- Javascript 自定义滚动条
- 使用javascript自定义href
- Javascript 自定义函数错误
- Javascript-自定义数组不起作用
- JavaScript自定义函数返回意外值
- 当数组的某些部分没有数据时,javascript自定义排序
- JavaScript 自定义警报框
- ...不是 JavaScript {自定义代码} 中的函数
- JavaScript 自定义事件或普通函数调用中哪个更好
- Javascript 自定义数组原型
- Javascript 自定义控制台.log
- 嵌套 Javascript 自定义事件
- 创建 JavaScript 自定义应用程序的新实例
- Javascript 自定义索引访问器
- 使用 JavaScript 自定义 URL
- Javascript 自定义十进制舍入方法
- Javascript 自定义事件侦听器不起作用