仅在第一个图像上设置jQuery attr()

Set jQuery attr() on first image only

本文关键字:jQuery attr 设置 第一个 图像      更新时间:2023-09-26

根据过去的问题,我知道你可以为页面上的现有元素设置一个新的attr(),比如页面上图像的ID,但在我的情况下,我只想为第一个图像设置ID。例如,剩下的4个没有添加此ID。

使用下面的代码,它会不断向页面上的所有图像添加ID。

<script>
    $( "img" ).attr( "id", "wp_featured_img" );
</script>

仅限第一个img

您可以使用jQuery:first选择器来实现这一点。你的代码应该是这样的:

<script>
    $( "img:first" ).attr( "id", "wp_featured_img" );
</script>

希望这能有所帮助!

使用:first选择器:

 $( "img:first" ).attr( "id", "wp_featured_img" );

其选择第一匹配的CCD_ 2元素。

使用

$( "img" ).first().attr( "id", "wp_featured_img" );

jsfiddle用于相同的