我有这段代码,我想让它尽可能的小。
正如你所看到的,我们重复了很多相同的HTML代码,但有一些小的变化。
<?php if( ! $liked_before): // If not liked before, show the link a href?>
<a href="javascript:;" id="action-like">
<div class="action_like" title="Like">
<abbr title="Like">Like</abbr>
</div>
</a>
<?php elseif($liked_before): // else dim it and make non clickable ?>
<p id="action-like" rel="liked_before">
<div class="action_like" title="You Like this" style="opacity: 0.5;">
<abbr title="You Like this">Like</abbr>
</div>
</p>
<?php endif; ?>
有点纠结于如何把它压缩成更少。
我后面也有和上面一样的代码,所以我有两个这样的if else语句。
如您所见,唯一改变的是:
- 将
a href=...
标签转换为p
标签 - 标题"Like"->"You Like this"
-
p
标签必须有rel,因为它在javascript中使用。
有什么办法让它更简洁吗?
某种内联回显。
你会怎么做?
我会让它保持原样。
从您的示例中,您还修改了<p>
或<a>
标记内的HTML(样式和缩写属性),并且将一些东西拼凑在一起来解决这个微不足道的"问题"只会导致可读性降低和更难管理代码。特别是从效率的角度来看,这样做没有什么好处。
这听起来可以使用更好的CSS来整理。你可以只使用类"喜欢"的标签来区分两者。非常整洁的代码,只有两个不同的a标记。
我会选择
- 跳过
else
条件,您不需要它。要么喜欢,要么不喜欢。 - 在这两种情况下都用p(或者更确切地说是div)来包装。
- 仅在检查时输出
a
元素。执行止回阀宽,一次开启,一次关闭。 - 使用CSS设置不透明度。
像这样?
<html><?php echo $booleanCondition ? '<b>blah</b>' : '<i>blah</i>';?><html>
为了在答案中列出实际答案:
创建一个函数来打印此内容,并在整个php文件中以一行代码的形式调用该函数。
像这样:
<?php
function getHtml($liked_before){
$title='';
$styleAttr='';
if( ! $liked_before){ // If not liked before, show the link a href
$title='Like';
}
else{ // else dim it and make non clickable
$title='You Like this';
$styleAttr=' style="opacity: 0.5;"';
}
$html='<div class="action_like" title="'.$title.'"'.$styleAttr.'><abbr title="'.$title.'">Like</abbr></div>';
if( ! $liked_before){ // If not liked before, show the link a href
$html='<a href="javascript:;" id="action-like">'.$html.'</a>';
}
else{ // else dim it and make non clickable
$html='<p id="action-like" rel="liked_before">'.$html.'</p>';
}
return $html;
}
?>