动态更改JS脚本src属性基于php Select

时间:2018-05-08 14:44:18

标签: javascript php html select

我有这个php代码,用select文件列表填充.js

<select id="s1" name="s1">
  <option value="" selected="selected">Select Employee</option>
    <?php
      foreach(glob(dirname(__FILE__) . '/*.js') as $filename){
        $filename = basename($filename, ".js");
        echo "<option value='" . $filename . "'>".$filename."</option>";
      }
      ?>
</select>

我稍后会在script标记上加载.js文件:

<script src="data.js"></script>

如何根据用户对文件的选择更改src属性并刷新页面以使用新的.js文件演示内容?

1 个答案:

答案 0 :(得分:0)

仅通过更改现有src的{​​{1}}属性无法工作,因为浏览器只会解析该元素一次。

相反,您需要创建一个全新的script元素,然后您可以有条件地配置src,然后将其附加到文档中。

script
src

但是,请注意,如果用户要从下拉列表中更改所选项目,则会创建另一个新的// Get a reference to the select var select = document.getElementById("s1"); // Set up a change event handler for it: select.addEventListener("change", function(){ // Create a new `<script>` element var script = document.createElement("script"); // Conditionally set the src for the element switch(this.value){ case "John" : script.src = "john.js"; break; case "Mary" : script.src = "mary.js"; break; case "Dave" : script.src = "dave.js"; break; } // Append the element to the document document.querySelector("head").appendChild(script); // Just for testing... scroll to the bottom to see the // newly created element console.log(document.querySelector("head").innerHTML); });元素,最后,您可以使用新的<select id="s1" name="s1"> <option value="" selected>Select Employee</option> <option>John</option> <option>Mary</option> <option>Dave</option> </select>每个项目。在这种情况下,您可能只想考虑静态链接到一个脚本文件并在其中包含不同的函数,然后根据下拉列表的值调用正确的函数。

相关问题