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

Is there a way to modify a specific attribute of every jquery object in one call?

本文关键字:jquery 修改 对象 属性 一次 方法 一种 有没有 调用      更新时间:2023-10-22

基本上。。。。我正在使用此代码

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都被设置为数组中第一个元素的数据加载文本。

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

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

函数的返回值用作每个元素的html()的值。

在注释中使用示例HTML:

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

可以,但您需要将类的名称更改为admin_editor_link,因为jQuery选择器正在尝试查找同时具有admin_editor_linkhtml类的元素。(当然,除非你真的在寻找同时具有这两个类的元素——你的问题没有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