代码之家  ›  专栏  ›  技术社区  ›  Ben

如何将span元素的HTML设置为自定义数据属性的内容?

  •  0
  • Ben  · 技术社区  · 12 年前

    我想显示一张表中的行数。我已经用PHP计算过了,并输出了 <span>200 rows total</span> ,但我想使用Javascript将其切换到 <span>Showing 2 of 200 total rows</span> 如果桌子被折叠。理想情况下,我想要这样的东西:

    $(".collapse-count").html('Showing 2 of ' + $(this).data("count") + ' total rows');
    

    带有标记:

    <span class="collapse-count" data-count="200">Showing 2 of 200 total rows</span>
    

    但这行不通。如何使用jQuery实现这一点?

    5 回复  |  直到 12 年前
        1
  •  2
  •   the system Amrendra    12 年前

    你需要使用 this 在适当的上下文中。

    $(".collapse-count").html(function() {
        return 'Showing 2 of ' + $(this).data("count") + ' total rows');
    });
    

    当您将回调传递给 .html() ,将迭代匹配的元素,并且 将是对迭代中当前元素的引用。

    按照您的方式,您使用的是的封闭值 .

        2
  •  2
  •   Ram    12 年前

    this 在您的代码中没有引用 .collapse-count 要素 html 方法在该函数的上下文中接受一个函数, 是指当前元素。

    $(".collapse-count").html(function(index, oldHTML) {
       return 'Showing 2 of ' + $(this).data("count") + ' total rows';
    });
    
        3
  •  2
  •   charlietfl    12 年前

    this 没有元素的上下文,就像您使用它的方式一样。

    您可以使用的回调函数参数 html() 方法:

    $(".collapse-count").html(function(){
        return 'Showing 2 of ' + $(this).data("count") + ' total rows';
    });
    
        4
  •  1
  •   Milind Anantwar    12 年前

    试试这个:

    $(".collapse-count").html(function() {
    return 'Showing 2 of ' + $(this).attr("data-count") + ' total rows';
    });
    
        5
  •  -2
  •   s_s_    12 年前

    使用 SPAN 你必须使用 .text() 而不是 .html()