需要你的一些专家帮助!
我有一个包含多个'div#gridContainer p'元素的页面。基本上我想找到p包含单词'Delivery'的那些,然后将变量'delivery'附加到匹配的所有元素。
这是我的代码到目前为止,但它不仅仅定位包含'delivery'的元素
if ($('div#gridContainer p:contains("Delivery")').length > 0) {
var delivery = 'image';
$('.deal_img').append(delivery);
}
任何帮助表示赞赏
答案 0 :(得分:1)
很抱歉听到您无法访问生成代码来修复错误的HTML输出。 ID的多次使用只是在寻找麻烦。但我认为以下单行jQuery调用将产生您正在寻找的影响:$('div#gridContainer p:contains("Delivery") span.deal_img').append('image');
实例,在Firefox 17,IE8和Chrome 30中测试:
<div id="gridContainer"><p>This paragraph contains the word Delivery<span class="deal_img"></span>.</p></div>
<div id="gridContainer"><p>This paragraph does not contain the key word<span class="deal_img"></span>.</p></div>
<div id="gridContainer"><p>This paragraph also contains the word Delivery<span class="deal_img"></span>.</p></div>
<div id="gridContainer"><p>Neither does this paragraph does not contain the key word<span class="deal_img"></span>.</p></div>
<script type="text/javascript">
$('div#gridContainer p:contains("Delivery") span.deal_img').append('image');
</script>
更新:我稍微调整了一下我的答案。此外,由于您似乎想要将图像附加到<span>
上,并附上“”deal_img“类,我添加了JSFiddle with a more comprehensive JQuery solution
答案 1 :(得分:0)
一种方法(我强烈地,强烈建议您尽一切可能修改HTML以符合标准,只是为了使您的工作更轻松,结果更可预测,跨浏览器兼容):
var text = 'image';
$('div[id="gridContainer"] p').each(function(i,e){
var self = e;
$(self).find('.deal-img').text(function(index,oldText){
return self['textContent' || 'innerText'].indexOf('Delivery') > -1 ? text : oldText;
});
});
以上内容基于以下HTML,因为您拒绝发布任何自己的HTML,以帮助我们为您提供帮助:
<div id="gridContainer">
<p>Delivery</p>
<p>Something else entirely</p>
</div>
<div id="gridContainer">
<p>Delivery <span class="deal-img">I have <em>no</em> idea about most of this question</span>
</p>
<p>Something else entirely</p>
</div>
<div id="gridContainer">
<p>Something else entirely</p>
</div>
<div id="gridContainer">
<p>Delivery <span class="deal-img">guessing where this element should go</span>
</p>
<p>Something else entirely</p>
</div>
参考文献: