简体   繁体   English

jQuery仅将属性应用于第一个元素?

[英]jquery apply an attribute to only the first element?

I'm trying to set an a name to the first link with a specific class, but I'm kinda unsure as to how to apply something to just the first one? 我正在尝试为特定类的第一个链接设置一个名称,但是我不确定如何将某些内容仅应用到第一个链接?

So, I'm trying to find the first div with the sample class and then wrap the text within the div.title with the : 因此,我试图找到带有示例类的第一个div,然后使用:将文本包装在div.title中。

<div class="sample">
<div class="title"><a name="thisone">title</a></div>
<p>blah blah</p>
</div>

<div class="sample">
<div class="title">title</div>
<p>blah blah</p>
</div>

<div class="sample">
<div class="title">title</div>
<p>blah blah</p>
</div>

This works for me: 这对我有用:

$("div.sample:first div.title").contents().wrap("<a name='thisone'></a>");

It finds the first <div> with class sample . 它使用类sample找到第一个<div> Inside it finds the divs with class title and wraps their contents in a link. 在其中找到具有类title的div,并将其内容包装在链接中。

Will that <a> be there already? <a>会在那里吗? If so: 如果是这样的话:

$('.sample:first .title a').attr('name', 'thisone');

If you don't have the <a> there to start with and want to wrap it in, use this: 如果您没有<a>开头并想将其包装,请使用以下命令:

$('.sample:first .title').wrap('<a name="thisone" />')

(live example) (实时示例)

您需要类似:

$('a:first').attr('name', 'thisone');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM