在jQuery中尝试以元素为目标时遇到困难

在jQuery中尝试以元素为目标时遇到困难,jquery,Jquery,我真的很难在jQuery中找到一个元素,希望能得到一些帮助,看看这是否可行 我的HTML是这样的结构 <p>Slimming World Nutritionist Jenny Allan says: “Ban the ‘D’ word. It has so many negative associations for most people, making them think of being deprived and not being able to share meals w

我真的很难在jQuery中找到一个元素,希望能得到一些帮助,看看这是否可行

我的HTML是这样的结构

<p>Slimming World Nutritionist Jenny Allan says: “Ban the ‘D’ word. It has so many negative associations for most people, making them think of being deprived and not being able to share meals with family and friends and enjoy social events.”</p>
<p style="text-align: center;">
    <div class="pinit aligncenter" data-indexer="1">
    <div class="img-caption">Lose weight and feel great a your wedding!</div>
    <div class="clear"></div>
    <noscript><img class="aligncenter size-full wp-image-33687" title="Lose weight and feel great a your wedding!" alt="danielle-david-real-wedding-05" src="http://www.giraffetest.co.uk/wp-content/uploads/2013/05/danielle-david-real-wedding-05.jpg" width="650" height="433" /></noscript>
</p>
<h2>Myth 4 – Healthy eating is expensive</h2>
<div data-indexer="2"></div>
<p>“Your weekly shop will go further, your overall food bills won’t go up – and neither will your weight.”</p>`
有人能帮忙吗

谢谢

詹姆斯

你可以做:

jQuery(".pinit").each(function() {
    if (jQuery(this).parent().next("h2").length) {
        jQuery(this).children("img").css("marginBottom", "0");
    }
});

基本上,
filter
用于将
.pinit
元素集过滤到只有父元素后跟
h2
的元素。然后剩下的
.pinit
元素应用了
css

您当前所做的是针对
h2
并对其应用样式。我建议运行一个
if
,然后应用你的风格。非常感谢-如果我想在pinit类div中定位一个img呢?我需要使用.children()选择器吗?只测试.length已经起作用了。不需要“>0”我是否需要更改.parent()以及我认为目标“.pinit img”将更改节点级别?@JamesPayne--忽略我之前关于选择器的评论,您使用的
.children()
,这是一个快速修复方法。看看新的答案。
jQuery(".pinit").each(function() {
    if (jQuery(this).parent().next("h2").length) {
        jQuery(this).children("img").css("marginBottom", "0");
    }
});
jQuery(".pinit").filter(function(){
    return jQuery(this).parent().next("h2").length > 0;
}).css("marginBottom", "0");