【问题标题】:Using the this keyword with jQuery selectors在 jQuery 选择器中使用 this 关键字
【发布时间】:2015-08-22 11:34:01
【问题描述】:

有人可以帮我解决使用jQuerythis关键字的syntax吗?

这是我的有效代码:

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 内容的格式不正确。

谢谢

【问题讨论】:

  • 请同时发布您的 html
  • 我建议你看看jQuery's .find()。如果您只想在子树中进行选择器搜索,这就是您想要的。 this 不参与此类活动。

标签: jquery jquery-selectors this


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    其实那是jQuery选择器的错误用法。

    jQuery 将当前文档对象分配给此“选择器”内的this

    http://jsfiddle.net/8rLdwr5w/1/
    看看这个样本。这里 jQuery 对象包含整个文档,我可以使用 find 方法访问外部 div

    如果您希望 jQuery 选择被调用一次然后重复使用,请遵循 Stuart Wagner 的方法。

    【讨论】:

      【解决方案3】:

      this 指向 jquery 中的当前对象,只有在语法错误时才会出错。 你应该试试这个。

      $(this).find('.info-box').addClass(obj.boxcolor); 要么 $('.example_infobox1 > div[class= ".info-box"]').addClass(obj.boxcolor);

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

      【讨论】:

        猜你喜欢
        • 2010-09-19
        • 1970-01-01
        • 2012-09-10
        • 2011-01-28
        • 2011-11-08
        • 1970-01-01
        • 1970-01-01
        • 2010-10-24
        • 1970-01-01
        相关资源
        最近更新 更多