【问题标题】:document.getElementById().options.length displays last element selected from list bar rather than the current selectiondocument.getElementById().options.length 显示从列表栏中选择的最后一个元素,而不是当前选择
【发布时间】:2018-07-22 09:26:37
【问题描述】:

我有一个脚本,它允许从下拉选择中选择目录,然后在另一个下拉选择中显示其子目录。我正在尝试检查所选目录是否有子目录,如果有,则显示一条消息,指示是否有可用的子目录,即"no subdirs""subdirs"

问题是警报消息显示的是从目录下拉列表中选择的最后一个元素,而不是当前目录选择。

例如,如果当前选择的是目录 2,而之前的选择是目录 1,则为目录 1 显示 document.getElementById("subdir").options.length;,而不是目录 2。我不确定问题出在哪里,所以请帮忙将不胜感激,谢谢。

<script type='text/javascript'>
  $(function() {
    $("#dirs").on('change', function() {
      var Dir = $(this).val();
      //Make an ajax call 
      $("#subdir").html('<option>Loading...</option>');
      $.get("ajax.php?Dirs=" + encodeURIComponent(Dir), function(data) {
        $("#subdir").html(data);
      });
    });
  });
</script>
<script>
  function myFunction() {
    var y = document.getElementById("subdir").options.length;

    alert(y);

    if (y <= 1) {
      alert('no subdirs');
    } else if (y > 1) {
      alert('subdirs');
    }
  }
</script>
<select id="dirs" name="Dirs" onChange="myFunction()">
  <option value="" selected="selected" disabled="yes">Select Directory</option>
  <?php
     $dirs = glob("/*", GLOB_ONLYDIR);
     foreach($dirs as $val){
       echo '<option value="'.$val.'">'.basename($val)."</option>\n";
     }
  ?>
</select>
<select name="subdir" id="subdir" required>
  <option value="Select Sub Directory" selected="selected" disabled="yes">Select Sub Directory</value>
</select>

还有ajax.php:

<?php
/* AJAX check  */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

  //Check for passed dir exist 
  $folder = $_GET['Dirs'];

  if(!file_exists($folder)) {
    exit('Folder Not Found');
  }

  $out = '';

  $files = array_filter(glob($folder.'/*'), 'is_dir');
  echo '<option value="Select Sub Directory" selected="selected" disabled = "yes">Select Sub Directory</value>';

  foreach($files as $val){
    $out .= '<option value="'.$val.'">'.basename($val)."</option>\n";
  }

  //Output the file options
  exit($out);
}
?>

【问题讨论】:

  • &lt;/value&gt;?????
  • 因为您在 Ajax 调用返回之前正在阅读它...

标签: javascript php html ajax


【解决方案1】:

问题很简单;这一切都与时间有关

<select id="dirs" name="Dirs" onChange="myFunction()">

看到了吗?它的意思是每当您更改此选择框时,运行一个名为 myFunction() immediately --> 的函数,甚至在执行任何 ajax 之前!

function myFunction() {
    var y = document.getElementById("subdir").options.length;

    alert(y);

    if (y <= 1) {
    alert('no subdirs');
    }
    else if (y > 1) {
    alert('subdirs');
    }
}

看到它与#subdir 的内容有关,但仍然没有调用 ajax,我们仍然使用早先#dirs 的任何内容,简而言之,我们在#subdir 中有陈旧的数据 这就是为什么它总是向您显示以前的数据

如何解决? 只需从那里剪切它并将函数调用移动到 ajax 回调中

$( "#subdir" ).html( data ); 
 myFunction();
});

【讨论】:

  • 嘿,Viney,非常感谢您的投入和时间!,问题解决了 :)。
猜你喜欢
  • 2013-08-18
  • 1970-01-01
  • 2020-12-04
  • 2017-11-28
  • 1970-01-01
  • 1970-01-01
  • 2014-02-11
  • 2014-06-20
  • 1970-01-01
相关资源
最近更新 更多