如果变量不存在,如何不显示 html


How to not not display html if variable isn't there?

我有一个具有不同功能的网站,但是如果没有分配变量,我不希望显示功能。

例如,我的产品有一个精选列表,如下所示:

<h3>Specifications</h3>
<ul>
    <li class="element element-text first">
        <strong>Manufacturer: </strong><?php echo $manufactuer;?>
    </li>
    <li class="element element-text">
        <strong>Model #: </strong><?php echo $model;?>
    </li>
    <li class="element element-text">
        <strong>Previously Ran: </strong><?php echo $ran;?>
    </li>
    <li class="element element-text last">
</ul>    

在前端,如果没有分配变量,我不希望显示Model行。

<?php if (isset($model) && !empty($model)) : ?>
<li class="element element-text">
  <strong>Model #: </strong>
  <?php echo $model;?>
</li>
<?php endif; ?>

你可以这样做

  <?php if(isset($model)): ?>
          <li class="element element-text">
          <strong>Model #: </strong><?php echo $model;?>
        </li>
  <?php  endif; ?>

你可以做到,

<?php echo (!empty($model))?$model:'';?>

继续阅读:空和三元运算符

当你

开始页面时,你需要使用 JavaScript 来编写 HTML。你可能想要这样的东西(确保你有一个名为JQuery的脚本,你可以在网上找到它):

$.ajax({ url: '/my/site.php',
    datatype: "JSON", /* Personal preference */
    type: 'get',
    cache: false,
    success: function(data) {
        alert(output);
        if(data[1] != null){
            document.getElementById('ID').innerHTML = "<li>" + data[1] + "</li>";
        } else {
            console.log("nothing found");
        }
    }
});

您可能需要针对您的特定代码编写进行一些调整,但我认为这是您需要的方法。一般来说,动态元素(那些不是静态的,即响应HTML之外的东西的元素)需要在JavaScript中处理。

完整的代码如下:

<h3>Specifications</h3>
        <ul>
            <?php if(isset($manufacturer) && !empty($manufacturer)): ?>
                <li class="element element-text first">
                    <strong>Manufacturer: </strong><?php echo $manufactuer;?>
                </li>
            <?php endif; ?>
            <?php if(isset($model) && !empty($model)): ?>
                <li class="element element-text">
                    <strong>Model #: </strong><?php echo $model;?>
                </li>
            <?php endif; ?>
            <?php if(isset($ran) && !empty($ran)): ?>
                <li class="element element-text">
                    <strong>Previously Ran: </strong><?php echo $ran;?>
                </li>
            <?php endif; ?>
            <li class="element element-text last"></li>
       </ul>