简体   繁体   中英

show hidden div section based on if statement

I have a few hidden divs on page like this

<div class="form" id="scheduler" style="display: none;">

<div class="form" id="test" style="display: none;">

<div class="form" id="super" style="display: none;">

I would like a jscript which can be called to show these hidden divs based on criteria like this

<?php 
if ($_GET['id'] == 'scheduler') {
   call jscript function (show div id:scheduler in this case)
}
else if ($_GET['id'] == 'test') {
   call jscript function (show div id:test in this case)
}
else if ($_GET['id'] == 'super') {
   call jscript function (show div id:super in this case)
}
?>

thanks.

you cannot call javascript function from PHP, PHP is server side based and stands for Preprocesing Hypertext while Javascript is browser based.

You could use:

<?php 
    if ($_GET['id'] == 'scheduler') {
       $showdiv = 'scheduler';
    }
    else if ($_GET['id'] == 'test') {
       $showdiv = 'test';
    }
    else if ($_GET['id'] == 'super') {
       $showdiv = 'super';
    }
    echo "<script type=\"text/javascript\">document.getElementById('".$showdiv."').style.display = 'block';</script>";
?>

but that should be at bottom of the page, after those divs are loaded.

<script type='text/javascript'>
function showDivById(id){
    document.getElementById(id).visible = true;
}

<?php 
    $divs = array('scheduler','test','super');
    if (array_seach($_GET['id'], $divs)!==false)
        echo "showDivById({$_GET['id']})";
?>
</script>

Note that php code is within the <script>

Why don't you write your function to accept the id param of the query string? <script>thefunction($get);</script>

This way you can save on if logic, and develop a more abstract function. It's less code, and easier to manage.

First of all. I would use jquery to show/hide divs...

but my concept would be a bit different then above,

<?php
  if($_GET['id']){
    echo '<script type="text/javascript">$(\'#'.$_GET['id'].'\').show();</script>';
  }
?>

Hope that you got my idea, it's clean and pretty dynamic :)

Even though you've accepted an answer, another option would be to use only JavaScript with the aid of some JS to easily retrieve values from the query string.

function $get(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split('&');
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');
    if (pair[0] == variable) {
      return pair[1];
    }
  }
}

var qs_id = $get('id');

if (['scheduler', 'test', 'super'].indexOf(qs_id) >= 0) {
  document.getElementById(qs_id).style.display = 'block';
}

Demo: jsfiddle.net/Marcel/L69xt/show

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM