[英]Load Javascript file depending on parent div id
--- 根據人們所說的 ---
這適用於多頁表單,它在 DOM 中加載多個頁面。 DOM 加載 page_2_2 和 page_3_3 但是,其中一個具有 display:none 樣式屬性,而另一個則沒有。 腳本是否可以通過一種方式來檢查哪個具有顯示:無然后加載適當的 Javascript 文件? 例如:
如果 DIV ID=page_2_2 有 style="display:none",那么加載 page2.js 否則加載 page1.js?
我有兩個 Javascript 文件...稱為 page1.js 和 page2.js。
我需要一個基於 Javascript 的 if function 表示
如果父DIV ID = page_2_2,則加載page1.js,如果父DIV ID = page_3_3,則加載page2.js,否則不加載任何內容。
function loadscript(divID) {
var scriptURL;
if (divID == "page_2_2")
scriptURL = "page1.js";
else if (divID == "page_3_3")
scriptURL = "page2.js";
$.getScript(scriptURL);
}
這並不復雜,function 獲取字符串作為參數。
loadscript("page_2_2") // will load page1.js
loadscript("page_3_3") // will load page2.js
您將什么類型的 elementid 作為字符串參數傳遞並不重要。
編輯:
據我了解,您有兩個 div,其中一個以“無”作為顯示值,因此您可以這樣做。
<div id="page_2_2" style="display:none"></div>
<div id="page_3_3"></div>
$(document).ready(function() {
if ($('#page_2_2').is(':visible'))
$.getScript("page1.js");
else
$.getScript("page2.js");
});
只需運行檢查然后加載
if($('#page_2_2').is(":visible")){
$.getScript("/page1.js", function(data, textStatus, jqxhr) {
console.log(data); //data returned
console.log(textStatus); //success
console.log(jqxhr.status); //200
console.log('Load was performed.');
});
}else if($('#page_3_3').is(":visible")){
$.getScript("/page2.js", function(data, textStatus, jqxhr) {
console.log(data); //data returned
console.log(textStatus); //success
console.log(jqxhr.status); //200
console.log('Load was performed.');
});
}
您可以檢查 div id,然后將腳本節點注入 header。我自己沒有測試過。
if($('#[insert id]').length != 1){ inject script etc }
我建議使用基於功能的方法,根據使用目的而不是使用位置,將邏輯放在不同的文件中。
示例文件結構:
/腳本/Utils.js
/Scripts/SpecificEditor.js
/腳本/所見即所得.js
在需要所見即所得的頁面上,您將引用 Wysiwyg.js,在需要“SpecificEditor”的頁面上,您將引用“SpecficEditor.js”。
使用您的方法,您的站點在增長時將難以管理。 例如,您如何在頁面之間共享邏輯?
這應該可以解決問題:
function loadScript(filename){
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
document.getElementsByTagName("head")[0].appendChild(fileref)
}
if(document.getElementById("page_2_2")===null){
loadScript("page1.js");
}else if(document.getElementById("page_3_3")===null){
loadScript("page2.js");
}
jQuery 變得稍短,將 if-else-if 塊轉換為:
if($(".page_2_2").length==0){
loadScript("page1.js");
}else if($(".page_3_3").length==0){
loadScript("page2.js");
}
您不清楚“父”div 的含義。 在這種情況下,如果該頁面上的任何div 具有該 id,這將加載腳本。 您不應該擁有多個具有相同 ID 的元素,所以我想這沒問題。 否則 jQuery closest()
方法將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.