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

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?

图片转代码服务由CSDN问答提供 功能建议

我有以下echo语句:

  echo'&lt  ; li&gt;&lt; a href =“'。esc_url(add_query_arg('booking-id',$ the_query-&gt; post-&gt; ID,site_url('/ pay-deposit /')))。'”&gt;支付 存款&lt; / a&gt;&lt; / li&gt;'; 
   
 
 

我想在参数= 1时将“禁用”类添加到链接中

以下是我尝试使用三元运算符

  $ is_deposit_paid = get_post_meta($ the_query-&gt; post-&gt; ID,'deposit_paid',  true); 
 echo'&lt; li&gt;&lt; a'。($ is_deposit_paid = 1)?  “残疾人”。'  href =“'。esc_url(add_query_arg('booking-id',$ the_query-&gt; post-&gt; ID,site_url('/ pay-deposit /')))。'”&gt;支付押金&lt; / a&gt;&lt;  ; / li&gt;'; 
   
 
 

但是这会产生语法错误。 如何正确写出来?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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>';
    
    点赞 打赏 评论
  • dsx666666 2015-12-01 19:12

    Just use a variable right after your function call with the class being "disabled" or nothing (""):

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

    If you only need the class, you could even check the function call immediately:

    $class = (get_post_meta( $the_query->post->ID, 'deposit_paid', true ))?"disabled":"";
    
    点赞 打赏 评论

相关推荐 更多相似问题