簡體   English   中英

基於php Select動態更改JS腳本src屬性

[英]Dynamically Change JS Script src Attribute Based on php 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>

我稍后會在加載.js文件時使用此script標簽:

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

如何根據用戶對文件的選擇來更改src屬性,並刷新頁面以使用新的.js文件演示內容?

僅通過更改現有scriptsrc屬性就無法工作,因為瀏覽器只會解析該元素一次。 解析后更改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> 

但是,請考慮一下,如果用戶要從下拉菜單中更改選定的項目,則會創建另一個新的script元素,最后,您可以為每個項目使用一個新的script 在這種情況下,您可能只想考慮靜態鏈接到一個腳本文件並在其中包含不同的功能,然后僅基於下拉列表的值調用正確的功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM