当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Hide Div if no image in the loop

问题描述:

Im looking to create a condition in wordpress loop. if no image then image box (.thumbHome{display:none})

this is in my 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>';

}

}

And my javascript:

window.onload = noImage();

function noImage(){

document.getElementByClassName('.thumbHome').css.display = 'none';

}

I tried:

window.onload = noImage();

function noImage(){

$('.thumbHome').addClass('hide');

}

RESULT: class hide added to all loop

I cant figure it another way, since im still new in coding.

thx

网友答案:

Well first of all, you don't want to call these functions on window.onload. That's going to immediately set all class instances of .thumbHome to hidden without any conditions.

Here's a very easy way to fix this issue. There are probably more intricate ways, but this works well.

In your main loop, add an unique id to each .thumbHome div based on the image id. So like:

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

Then your else conditional (for whether there's a thumbnail) could be changed to:

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

and your js function could be:

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

This is not necessary the best way to do this, it's just the best way with the situtation you find yourself in now.

分享给朋友:
您可能感兴趣的文章:
随机阅读: