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

有没有方法在一次调用中修改每个jquery对象的特定属性?

  •  1
  • Marie  · 技术社区  · 11 年前

    大体上我正在使用此代码

    var editorLinks;
    editorLinks = $(".admin_editor_link.html");
    $.each(editorLinks, function(i, link){
        $(link).html($(link).attr("data-loadedtext"));
    }); 
    

    我想知道是否有一些方法可以做到这一点,而不需要每次通话。。。喜欢

    editorLinks.html($(this).attr("data-loadedtext"));
    

    我假设这会起作用(或者我不记得它的一些变体),但当我尝试时,所有元素html都设置为数组中第一个元素的数据加载文本。

    2 回复  |  直到 11 年前
        1
  •  2
  •   iCollect.it Ltd    11 年前

    使用提供给的函数 html() :

       editorLinks.html(function(){
            return $(this).attr("data-loadedtext");
       });
    

    函数的返回值用作 html() 对于每个元素 .

    在注释中使用示例HTML:

    JSFiddle: http://jsfiddle.net/TrueBlueAussie/taesc0tt/2/

        2
  •  1
  •   Andy    11 年前

    是的,您可以,但您需要将类的名称更改为 admin_editor_link 因为jQuery选择器试图查找同时具有 管理员编辑器链接 html 类。(当然,除非您实际上在寻找具有这两个类的元素——您的问题没有HTML代码来验证这一点——在这种情况下,您是可以的)。

    <div data-loadedtext="1" class="admin_editor_link"></div>
    <div data-loadedtext="2" class="admin_editor_link"></div>
    

    只需使用函数返回结果

    var editorLinks = $(".admin_editor_link");
    
    editorLinks.html(function () {
      return $(this).attr("data-loadedtext");
    });
    

    DEMO

    DEMO with both classes