2010-02-01 42 views
1
$(function(){ 
     $(".test").each(function(){ 
      test(); 
     }); 
    }); 

    function test(){ 
     $(this).css("border","1px solid red").append(" checked"); 
    } 

爲什麼這不起作用?我錯過了什麼? 這是我測試的HTML:jQuery與每個()和自定義函數的問題

<p>test</p> 
    <p>test</p> 
    <p class="test">test</p> 
    <p>test</p> 

回答

5

的$(本)不能以這種方式被使用,因爲你不指定測試()函數的上下文:

$(".test").each(function(){ 
     test($(this)); 
}); 

function test(el){ 
    el.css("border","1px solid red").append(" checked"); 
} 

$(".test").each(function(){ 
     test.call(this); 
}); 
function test(){ 
    $(this).css("border","1px solid red").append(" checked"); 
} 
+0

太棒了!非常感謝你! 這就是我需要的! – thetester 2010-02-01 11:44:38

1

內部測試功能,this不綁定到你認爲它一定是一樣的。使用像螢火蟲這樣的調試器來查看你實際使用的是什麼。

這樣做的慣用方法是簡單地在封閉內部包含測試主體(function(){...})。

其他解決方案,您可以使用apply函數(https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Function/Apply)來控制this引用的內容。在這種情況下,這是過分的,實際上,我發現最好避免它。

$(function(){ 
     $(".test").each(function(){ 
      $(this).css("border","1px solid red").append(" checked"); 
     }); 
    }); 
+0

如果我們只需要一次函數,那麼匿名函數將所有的邏輯保存在一個地方。 – DavidA 2010-02-01 11:48:33

0

要麼test.call(this);test(this);並更改定義。