2014-06-05 24 views
0

不知道這是可能的,我的編輯高亮似乎並不這麼認爲......我試圖運行相同的代碼,在內置函數像previousSibling,nextSibling(我有其他場景,其中循環不同的功能會有所幫助)。即使有一個內置的函數,我不知道可以爲我刪除節點之間的空間(請讓我知道是否有),我想知道是否將函數作爲參數,然後用另一個元素調用它以獲得價值是可能的。之前的兄弟和nextSibling能夠在「輸入」上被調用,所以爲什麼不能這樣工作?如何將一個函數作爲參數傳遞給自定義函數在Javascript

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> 
+0

JavaScript函數是對象。你可以將它們作爲參數傳遞。 –

+0

@ PM77-1 你是說我的問題的標題是錯的,或者是代碼沒有正確地做某件事? – user3334776

+0

也沒有。我只是確認函數可以作爲參數傳遞。參見[作爲參數的javascript通函數(http://stackoverflow.com/questions/13286233/javascript-pass-function-as-parameter。) –

回答

0

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的特性它會在你的情況下,更容易通過屬性名稱,並使用bracket notation來訪問它們:

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作爲條件本身(如上面我的示例中所示)

+0

謝謝,這真的有幫助。爲什麼以這種方式循環可怕? – user3334776

+0

因爲它太複雜了。太容易發生錯誤導致無限循環。 – Bergi

+0

大聲笑,我明白了你的觀點,再次感謝! – user3334776

相關問題