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

标签 jquery jquery-selectors this

有人可以帮助我了解使用 jQuery this 关键字的语法吗?

这是我的有效代码:

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);

这是我正在编写的代码:

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);
}   

我在控制台中没有收到任何错误,但是 html 内容的格式不正确。

谢谢

最佳答案

我认为在这种情况下使用变量会更好。

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);

关于jquery - 将 this 关键字与 jQuery 选择器一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30701732/

相关文章:

javascript - 在 Twitter Bootstrap 3 中切换类时的过渡

javascript - jQuery 上下文菜单获取被单击的项目

Click 上的 Jquery 动态选择器

javascript - _.each(list, iterator, [context]) 中的上下文是什么?

javascript - 如何在内部类中找到正确的 "this"对象?

Reactjs - 方法给出错误

javascript - 我创建了一个 jQuery 幻灯片,但它不断重复相同的图像

javascript - html/php表单计算简单公式的显示结果

javascript - 如何调试 JSONP AJAX 事件

javascript - 多个 jQuery 选择器的最佳语法实践