Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/84.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
在使用after时在jquery函数中使用此选项_Jquery - Fatal编程技术网

在使用after时在jquery函数中使用此选项

在使用after时在jquery函数中使用此选项,jquery,Jquery,我经常看到在jquery中使用this是$(this),但这里使用的是this $(“p”)。在(函数()之后{ 返回“+this.className+”; }); 如果我像这样使用,它就不起作用了 $( "p" ).after(function() { var cnam = $(this).class(); return "<div>" + cnam + "</div>"; }); $(“p”)。在(函数()之后{ var cnam=$(this.

我经常看到在jquery中使用this是
$(this)
,但这里使用的是
this

$(“p”)。在(函数()之后{
返回“+this.className+”;
});
如果我像这样使用,它就不起作用了

$( "p" ).after(function() {
    var cnam = $(this).class();
    return "<div>" + cnam + "</div>";
});
$(“p”)。在(函数()之后{
var cnam=$(this.class();
返回“+cnam+”;
});

还有一个问题,为什么插入的div没有红色背景?

您没有任何
类()

你可以用

$(this).attr('class');

获取类。

这是一个具有属性的DOM元素

jQuery不公开
.class()
方法。但是,它确实有
$(element).prop('class')

将DOM元素转换为jQuery对象:

var $el = $(this);
或者反过来说:

var el = $(this)[0]; //or var el = $(this).get(0);

你需要这样做

$( "p" ).after(function() {
    var cnam = $(this).attr('class');
    return "<div>" + cnam + "</div>";
});
$(“p”)。在(函数()之后{
var cnam=$(this.attr('class');
返回“+cnam+”;
});

Jquery没有
.class()

这样的函数,为什么插入的div没有红色背景?因为它没有
foo
className。为什么像jquery中所描述的那样在这里使用“this”,我们使用时它应该使用$(this)?@未定义。在我的示例中,after()只选择类名并插入文本……
$(this)
这个
的包装器,这样您就可以使用
jQuery
了,您希望得到什么?您不向元素添加任何类名,
引用回调中的DOM元素对象。如果要创建jQuery对象,请使用
$()
包装它。
$( "p" ).after(function() {
    var cnam = $(this).attr('class');
    return "<div>" + cnam + "</div>";
});