Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在getter之后调用Jquery方法_Javascript_Jquery - Fatal编程技术网

Javascript 在getter之后调用Jquery方法

Javascript 在getter之后调用Jquery方法,javascript,jquery,Javascript,Jquery,我在查看jQuery文档。我发现了这个例子 为什么这个代码不起作用? getter和setter如何使用jQUery 编辑 如果我想将类添加到特定的标记中,那么如何实现它呢 这将不起作用,因为$(选择器).html()返回一个字符串值,该值构成所选元素的html内容。字符串没有addClass函数 编辑:为了响应您的编辑,只需翻转函数调用的顺序即可 $("h1").addClass("test").html() html()返回字符串,所以不能调用假定在jQuery对象上运行的addClass

我在查看jQuery文档。我发现了这个例子

为什么这个代码不起作用? getter和setter如何使用jQUery

编辑

如果我想将类添加到特定的标记中,那么如何实现它呢


这将不起作用,因为
$(选择器).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方法