【问题标题】:Hide Div if no image in the loop如果循环中没有图像,则隐藏 Div
【发布时间】:2011-01-11 20:53:26
【问题描述】:

我希望在 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');
} 

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

我想不出另一种方式,因为我还是编码新手。

谢谢

【问题讨论】:

  • 如果实际上有任何图像,您始终可以将框默认为隐藏,并在循环完成后简单地发出覆盖 css。你已经拥有了服务器端的所有信息,不妨利用它。当然,使用 javascript 的人不会看到任何图片,但这是他们的问题。

标签: php javascript wordpress


【解决方案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 条件(是否有缩略图)可以更改为:

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

你的js函数可能是:

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

这不一定是最好的方法,它只是你现在所处情况的最好方法。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 2017-04-24
相关资源
最近更新 更多