doukao2180 2015-12-01 19:02
浏览 197
已采纳

if使用三元运算符在echo中的语句

I have the following echo statement:

echo '<li><a href="'. esc_url(add_query_arg( 'booking-id', $the_query->post->ID, site_url( '/pay-deposit/' ) )) .'">Pay deposit</a></li>';

I want to add the class "disabled" to the link when a parameter = 1

Here is what I am trying using ternary operators

    $is_deposit_paid = get_post_meta( $the_query->post->ID, 'deposit_paid', true );
    echo '<li><a '.( $is_deposit_paid = 1) ? "disabled" .' href="'. esc_url(add_query_arg( 'booking-id', $the_query->post->ID, site_url( '/pay-deposit/' ) )) .'">Pay deposit</a></li>';

however this produces a syntax error. How do I write this out correctly?

  • 写回答

2条回答 默认 最新

  • dpecb06062 2015-12-01 19:13
    关注

    There are three issues to solve:

    • ternary operator requires ... 3 arguments (surprise!), so after the second, you need to add the : and the string you want in the else case.

    • the whole ternary expression should be put in brackets (not the condition) before you apply the dot operator to it in building your string.

    • You need to compare, not assign (== instead of =)

    So this would do it:

    $is_deposit_paid = get_post_meta( $the_query->post->ID, 'deposit_paid', true );
    echo '<li><a '.( $is_deposit_paid == 1  ? "disabled" : "") . 
        ' href="'. esc_url(add_query_arg( 'booking-id', $the_query->post->ID, 
            site_url( '/pay-deposit/' ) )) . 
        '">Pay deposit</a></li>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改