Javascript 在getter之后调用Jquery方法
我在查看jQuery文档。我发现了这个例子 为什么这个代码不起作用? getter和setter如何使用jQUery 编辑 如果我想将类添加到特定的标记中,那么如何实现它呢Javascript 在getter之后调用Jquery方法,javascript,jquery,Javascript,Jquery,我在查看jQuery文档。我发现了这个例子 为什么这个代码不起作用? getter和setter如何使用jQUery 编辑 如果我想将类添加到特定的标记中,那么如何实现它呢 这将不起作用,因为$(选择器).html()返回一个字符串值,该值构成所选元素的html内容。字符串没有addClass函数 编辑:为了响应您的编辑,只需翻转函数调用的顺序即可 $("h1").addClass("test").html() html()返回字符串,所以不能调用假定在jQuery对象上运行的addClass
这将不起作用,因为
$(选择器).html()
返回一个字符串值,该值构成所选元素的html内容。字符串没有addClass
函数
编辑:为了响应您的编辑,只需翻转函数调用的顺序即可
$("h1").addClass("test").html()
html()返回字符串,所以不能调用假定在jQuery对象上运行的addClass方法
这是因为html()
返回一个字符串。就像
$( "h1" ).html().addClass("test");
// is like
var test1 = $( "h1" ).html();
test1 = test1.addClass( "test" ); // will fail because string has no addClass
$( "h1" ).addClass( "test" ).html();
// is like
var test1 = $( "h1" ).addClass( "test" ); // test1 is a jQuery object of h1
test1 = test1.html(); // success, because test1 is a jQuery object (has .html()).
但是如果您先addClass
,它将向h1
添加一个类,并返回h1
的jQuery对象,因此我们仍然可以在其上使用html()
。就像
$( "h1" ).html().addClass("test");
// is like
var test1 = $( "h1" ).html();
test1 = test1.addClass( "test" ); // will fail because string has no addClass
$( "h1" ).addClass( "test" ).html();
// is like
var test1 = $( "h1" ).addClass( "test" ); // test1 is a jQuery object of h1
test1 = test1.html(); // success, because test1 is a jQuery object (has .html()).
在jQuery中,getter获取某些信息。例如,上面的getter获取$(“h1”)
jQuery对象的innerHTML
属性
另一方面,setter更改元素中的信息。setter将更改信息,然后返回新的jQuery对象。对于所有(或至少大多数)不是getter的jQuery方法也是如此
因为不带参数的.html()
是一个getter,所以它返回一个字符串,而不是jQuery对象。但是,如果将.html()
方法用作带参数的setter,它将返回jQuery对象。方法返回的jQuery对象的方法就是这样工作的:您可以在一行代码中一个接一个地调用方法,因为这些方法返回jQuery对象。但是,如果其中一个方法是getter,则这不起作用
$("h1").html().addClass(test); //TypeError: undefined is not a function (Chrome)
$("h1").html("Hi!").addClass(test); //Perfectly valid
解释如何链接jQuery方法