基本上,我尝试使用 jquery 获取一个类的内容,然后将相同的数据附加到其他地方。存在多个具有相同类名的内容。我将借助图像来说明它。
我试图通过使用jquery选择器来实现这一点,但我陷入了一个困境,我必须在具有相同类名的不同元素中附加不同的内容。 让我用 animage( https://ibb.co/P1K2XWT ) 来解释。 您可以在这张图片中看到 3 张卡片,分别显示价格、名称和按钮。我必须获得该价格并且必须附加在名称(标题)下。 我有价格和名称,但我不知道如何逐卡查看并将每个价格附加在其下方。
var x =[];
$('.ld_course_grid_price').each(function(index, obj)
{
x.push($(this).text());
});
console.log(x);
var y =[];
$('.entry-title').each(function(index, obj)
{
y.push($(this).text());
});
HTML的结构
<article id="post-479" class="thumbnail course post-479 sfwd-courses type-sfwd-courses status-publish has-post-thumbnail hentry ld_course_category-algebra-1 ast-article-single">
<div class="ld_course_grid_price price_$">
$70
</div>
<a href="" rel="bookmark">
<img width="270" height="226" src="" class="attachment-course-thumb size-course-thumb wp-post-image" alt=""> </a>
<div class="caption">
<h3 class="entry-title">Basic Algebra</h3>
<p class="ld_course_grid_button"><a class="btn btn-primary" role="button" href="/courses/basic-algebra/" rel="bookmark">Enroll</a></p>
</div>
<!-- .entry-header -->
</article>
这就是我获取价格的方式。我必须将它们显示在标题下。
最佳答案
您想要循环更高级别的重复 <article>
然后在该元素实例中执行您需要执行的操作
$('article.sfwd-courses').each(function() {
var $article = $(this),
// look for what is needed in this article instance
price = $article.find('.ld_course_grid_price').text(),
title = $article.find('.entry-title').text();
// do something with what you found
var div = '<div style="color:red"> Title: ' + title + ', Price: ' + price + '</div>';
$article.after(div);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article id="post-479" class="thumbnail course post-479 sfwd-courses type-sfwd-courses status-publish has-post-thumbnail hentry ld_course_category-algebra-1 ast-article-single">
<div class="ld_course_grid_price price_$">
$70
</div>
<a href="" rel="bookmark">
<img width="270" height="226" src="" class="attachment-course-thumb size-course-thumb wp-post-image" alt=""> </a>
<div class="caption">
<h3 class="entry-title">Basic Algebra</h3>
<p class="ld_course_grid_button"><a class="btn btn-primary" role="button" href="/courses/basic-algebra/" rel="bookmark">Enroll</a></p>
</div>
<!-- .entry-header -->
</article>
关于javascript - 如何在具有相同类的 html 元素中单独添加/附加 html 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55600443/