jQuery 插入元素 .before() 和 .after() 无法按预期工作,我做错了什么?

发布于 2024-09-26 04:57:28 字数 988 浏览 0 评论 0原文

我试图用 div 标签动态包围 IMG 和 A 标签集,但无法使其工作。

我的 html:

<img class="myClass-1" src="img5" />
<a class="myClass-2" href="url"></a>  

我的脚本:

$('img.myClass-1').each(function(){
   $(this).before('<div style="position: relative;">');
   $(this).next().after('</div>');
});  

我的 Firebug 结果:

<div style="position: relative;"/>
<img class="myClass-1" src="img5" />
<a class="myClass-2" href="url"></a>  

我想要完成的任务:

<div style="position: relative;">
<img class="myClass-1" src="img5" />
<a class="myClass-2" href="url"></a>
</div>  

我替换

$(this).next().after('</div>');  

$(this).next().after('<p>test</p>');  

只是为了看看它是否无法执行 .next().after() 代码,但它工作正常。我是 jQuery 的新手,不知道我做错了什么。有人可以帮忙吗?请。

I am trying to dynamically surround sets of IMG and A tags with a div tag but am unable to make it work.

my html:

<img class="myClass-1" src="img5" />
<a class="myClass-2" href="url"></a>  

my script:

$('img.myClass-1').each(function(){
   $(this).before('<div style="position: relative;">');
   $(this).next().after('</div>');
});  

my Firebug outcome:

<div style="position: relative;"/>
<img class="myClass-1" src="img5" />
<a class="myClass-2" href="url"></a>  

What I am trying to accomplish:

<div style="position: relative;">
<img class="myClass-1" src="img5" />
<a class="myClass-2" href="url"></a>
</div>  

I replaced

$(this).next().after('</div>');  

with

$(this).next().after('<p>test</p>');  

just to see if it was unable to execute the .next().after() code but it works fine. I am new to using jQuery and can't figure out what I'm doing wrong. Can somebody help? Please.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

没企图 2024-10-03 04:57:28

您可以使用 .wrapAll(),如下所示:

$(this).next().andSelf().wrapAll('<div style="position: relative;" />');

您可以在此处进行测试,这需要 < a> 然后将它们包装在该

容器中。

You can use .wrapAll(), like this:

$(this).next().andSelf().wrapAll('<div style="position: relative;" />');

You can test it out here, this takes <img> and <a> then wraps them both in that <div> container.

夜血缘 2024-10-03 04:57:28

您还可以删除each()(或者只是将其替换为尼克代码片段中的选择器):

$('img.myClass-1').next().andSelf().wrapAll('<div style="position: relative;" />');

You could also get rid of the each() (or just replace this with your selector in Nick's snippet):

$('img.myClass-1').next().andSelf().wrapAll('<div style="position: relative;" />');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文