如何将属性值附加到页面上的每个元素?

时间:2022-02-04 14:26:46

I want to append a link to each element on a page that has the attribute name "data-update-id"

我想在页面上添加一个链接到属性名为“data-update-id”的页面上的每个元素

On the page there are multiple li elements like this:

在页面上有多个li元素,如下所示:

<li class="feed-update member-like-share  has-snippets" data-update="true" data-block="update" data-update-id="6029870346117619712" data-actor-type="member" data-li-utrk...

I want to grab the value of data-update-id for each one (eg 6029870346117619712) in the above example and append it to the li element. The added complication is that I want to append this number to a url and make it a link.

我想在上面的例子中获取每个数据的update-id值(例如6029870346117619712)并将其附加到li元素。增加的复杂性是我想将这个数字附加到一个url并使其成为一个链接。

The link is https://www.linkedin.com/nhome/updates?topic=, and so in the above example I'd like it to become https://www.linkedin.com/nhome/updates?topic=6029870346117619712

链接是https://www.linkedin.com/nhome/updates?topic=,所以在上面的例子中,我希望它成为https://www.linkedin.com/nhome/updates?topic=6029870346117619712

I tested the following to start with and it doesn't work:

我开始测试以下内容并且它不起作用:

 "li[data-update-id]").append($(this).attr("data-id"));

I'm still fairly new to jQuery, so be kind. I assume it doesn't work because I would need to loop round each element? Can you help?

我仍然是jQuery的新手,所以要善良。我认为它不起作用,因为我需要循环每个元素?你能帮我吗?

2 个解决方案

#1


1  

You may use each , html and using data to grab the data-* attribute.

您可以使用each,html和使用数据来获取data- *属性。

$("li[data-update-id]").each(function(){
   $(this).html($(this).data('update-id'));
});

#2


1  

You can use callback function provided for .text():

您可以使用.text()提供的回调函数:

$('li').text(function(i,oldtxt){
  return oldtxt + $(this).data("update-id");
});

Working Demo

#1


1  

You may use each , html and using data to grab the data-* attribute.

您可以使用each,html和使用数据来获取data- *属性。

$("li[data-update-id]").each(function(){
   $(this).html($(this).data('update-id'));
});

#2


1  

You can use callback function provided for .text():

您可以使用.text()提供的回调函数:

$('li').text(function(i,oldtxt){
  return oldtxt + $(this).data("update-id");
});

Working Demo