如果循环中没有图像,则隐藏Div

时间:2011-01-11 20:53:26

标签: php javascript wordpress

我希望在wordpress循环中创建一个条件。如果没有图像则图像框(.thumbHome {display:none})

这是我的function.php

function getThumbImages($postId) {
$iPostID = get_the_ID();
$arrImages =& get_children('post_type=attachment&post_mime_type=image&post_parent=' .   $iPostID );
if($arrImages) {
    $arrKeys = array_keys($arrImages);
    $iNum = $arrKeys[0];
    $sThumbUrl = wp_get_attachment_thumb_url($iNum, $something);
    $sImgString =  '<img src="' . $sThumbUrl . '" alt="thumb Image" title="thumb Image" />';
echo $sImgString;}
else {
echo '<script language="javascript">noImage()</script>';
}
}  

我的javascript:

window.onload = noImage();
 function noImage(){
document.getElementByClassName('.thumbHome').css.display = 'none';
}

我试过了:

window.onload = noImage();
function noImage(){
$('.thumbHome').addClass('hide');
} 

结果:类隐藏添加到所有循环

我无法用另一种方式来解释,因为我仍然是编码新手。

THX

1 个答案:

答案 0 :(得分:1)

首先,您不想在window.onload上调用这些函数。这将立即将.thumbHome的所有类实例设置为隐藏,无任何条件。

这是解决此问题的一种非常简单的方法。可能有更复杂的方法,但这很有效。

在主循环中,根据图像ID为每个.thumbHome div添加唯一ID。所以喜欢:

echo '<div class="thumbHome" id="thumb-' . $iNum . '"> ... </div>';
// or you could you use the post ID, doesn't matter, as long as you are consistent

然后您的其他条件(对于是否有缩略图)可以更改为:

else {
    echo '<script type="text/javascript">noImage("#thumb-' . $iNum . '")</script>';
}

你的js功能可能是:

function noImage(var){
    $(var).hide();
}

这不是实现这一目标的最佳方式,这是你现在所处的情绪最佳方式。