简体   繁体   English

将this关键字与jQuery选择器一起使用

[英]Using the this keyword with jQuery selectors

Can someone please help me with the syntax of using the jQuery this keyword? 有人可以帮我使用jQuery this关键字的syntax吗?

Here is my code that works: 这是我的代码有效:

var obj = jQuery.parseJSON(data);

$('.example_infobox1').addClass(obj.gridlayout);
$('.example_infobox1 .info-box').addClass(obj.boxcolor);    
$('.example_infobox1 .info-box-icon').addClass(obj.iconcolor);
$('.example_infobox1 i').addClass(obj.icon);
$('.example_infobox1 .info-box-text').html(obj.text);
$('.example_infobox1 .info-box-number').html(obj.number);

Here is the code that I am working on: 这是我正在处理的代码:

var obj = jQuery.parseJSON(data);

$('.example_infobox1')
{
    $(this).addClass(obj.gridlayout);
    $('.info-box', this).addClass(obj.boxcolor);    
    $('.info-box-icon', this).addClass(obj.iconcolor);
    $('i', this).addClass(obj.icon);
    $('.info-box-text', this).html(obj.text);
    $('.info-box-number', this).html(obj.number);
}   

I am not getting any errors in the console, however the html content is not being correctly formatted. 我在控制台中没有收到任何错误,但是html内容的格式不正确。

Thanks 谢谢

I think a variable would be better in this case. 我认为在这种情况下,变量会更好。

var box = $('.example_infobox1');

box.addClass(obj.gridlayout);
$('.info-box', box).addClass(obj.boxcolor);    
$('.info-box-icon', box).addClass(obj.iconcolor);
$('i', box).addClass(obj.icon);
$('.info-box-text', box).html(obj.text);
$('.info-box-number', box).html(obj.number);

Actually, that is the wrong usage of jQuery selector. 实际上,这是jQuery选择器的错误用法。

jQuery assignes current document object to this within this "selector". jQuery在此“选择器”中this分配当前文档对象。

http://jsfiddle.net/8rLdwr5w/1/ http://jsfiddle.net/8rLdwr5w/1/
Take a look at this sample. 看一下这个样本。 Here the jQuery object contains the whole document and I can access external div using find method. 这里的jQuery对象包含整个文档,我可以使用find方法访问外部div

If you want the jQuery selection to be called once and then reused, follow Stuart Wagner's approach. 如果要一次调用jQuery选择然后重用,请遵循Stuart Wagner的方法。

this points to current object in jquery and it gives an error only when syntax is wrong. 这指向jquery中的当前对象,并且仅当语法错误时才会给出错误。 your should try this. 您应该尝试一下。

$(this).find('.info-box').addClass(obj.boxcolor); $(本).find( '信息框。')addClass(obj.boxcolor)。 or $('.example_infobox1 > div[class = ".info-box"]').addClass(obj.boxcolor); 或$('。example_infobox1> div [class =“ .info-box”]')。addClass(obj.boxcolor);或

or 要么

$(".example_infobox1 ").children(".info-box").addClass( "obj.boxcolor"); $(“。example_infobox1”).children(“。info-box”)。addClass(“ obj.boxcolor”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM