问题描述
我的页面上有多个<p>
元素。
此<p>
元素中的数据来自数据库。
这是我的代码。
第一种<p>
元素
<p><img class="img img-responsive" src="image_url" alt="" width="235" height="41"></p>
具有style
属性的<p>
元素的第二种类型(此样式也来自数据库)
<p style="text-align: center;">
<img class="img img-responsive" src="image_url" alt="" width="235" height="41">
</p>
现在,我想向图像添加class
center-block
,其<p>
标签具有这样的样式属性。
<p style="text-align: center;>
我正在用下面的jQuery代码做到这一点。
<script>
$( "p" ).find( "img" ).addClass('center-block');
</script>
问题
但是问题在于类center-block
被应用于两个图像。
我想将此仅应用于<p>
元素的第二种类型的图像。
我怎样才能做到这一点?
1楼
仅在属性中检索具有该样式的段落(以text-align
开头)
$( "p[style^='text-align'] img" ).addClass('center-block');
在VanillaJS中 :
[].forEach.call(document.querySelectorAll("p[style^='text-align'] img"), function(el) {
el.classList.add('center-block');
})
2楼
您可以使用属性CSS选择器:
$('p[style="text-align: center"] img').addClass('center-block');
仅当整个样式都包含空格时,此方法才有效;如果您有其他样式,则可以使用此选择器
'p[style*="text-align: center"] img'
如果您不知道是否有空间,可以使用两个属性选择器:
'p[style*="text-align: center"] img, p[style*="text-align:center"] img'
您还可以编写自定义的伪选择器(在JavaScript中),例如:style(text-align: center)
,它更复杂,我认为您的情况不需要它。
旁注,正如您在我的代码中看到的那样,由于您不需要它,因此找不到,您可以使用单个选择器。
3楼
$("p").each(function(){
if($(this).css('text-align') == "center") {
$(this).find('img').addClass('center-block');
}
});
这将检查每个p元素以及样式中包含text-align的元素:center它将设置其子图像以包括center-block类
4楼
您应该使用过滤器功能
$( "li" )
.filter(function( index ) {
return $( this ).attr( "style" ) === "text-align: center";
})
.addClass('center-block');
5楼
只需选择检查css属性,使其text-align
匹配您提供的属性即可,这是一个有效的代码段:
$( document ).ready(function() { $( "p[style='text-align: center;']" ).find( "img" ).addClass('center-block'); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p><img class="img img-responsive" src="https://www.catster.com/wp-content/uploads/2017/08/A-fluffy-cat-looking-funny-surprised-or-concerned.jpg" alt="" width="235" height="41"></p> <p style="text-align: center;"> <img class="img img-responsive" src="https://www.catster.com/wp-content/uploads/2017/08/A-fluffy-cat-looking-funny-surprised-or-concerned.jpg" alt="" width="235" height="41"> </p>
6楼
我认为足以找到具有样式属性的所有p
<script>
$( "p[style] img" ).addClass('center-block');
</script>