问题1
我刚刚开始学习 jQuery,让我困惑的一件事是其中带有参数的 function()
,即:function(e)
。
[示例1]
$("#rating a").click(function(e){
// stop normal link click
e.preventDefault();
}
function(e)
中的 e
是什么?
[示例2]
$.post("test.php", function(data) {
alert("Data Loaded: " + data);
});
你怎么知道数据
是什么?我假设 data
与示例 1 中的 e
不同。
我很困惑为什么 function()
在不同的场景中是不同的......
问题 2
由于我们正在讨论基本的 jQuery,所以这里有另一个 jQuery 问题。 this
和 $(this)
有什么区别?
[示例3]
$(document).ready(function() {
// use this to reset several forms at once
$("#reset").click(function() {
$("form").each(function() {
this.reset();
});
});
[示例 4]
$("a").hover(function(){
$(this).parents("p").addClass("highlight");
},function(){
$(this).parents("p").removeClass("highlight");
});
});
最佳答案
function(e) -> this 将事件对象作为参数传递。如果没有 e,您就无法访问事件对象。
“this”是与您正在执行的操作相关的对象。如果你像 $(this) 一样包装“this”,那么你就可以访问 jQuery 提供的所有扩展。更清楚地说,“this”通常是一个 DOM 对象,$(this) 是一个 jQuery 对象。
关于javascript - jQuery 中的 function() 是什么意思?这和 $(this) 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6447739/