我正在構建一個WordPress插件,它允許用戶重新創建WordPress管理菜單。 WordPress提供了一個名爲global $submenu;
的全局變量,其中包含菜單的所有子菜單項。所以我開發了一個Javascript界面,允許人們編輯這個菜單。所以我需要做的是讓用戶編輯並將其重新推回到全局變量中。使用變量作爲對象名稱並將數組推入對象
當我輸出該變量到JavaScript控制檯我得到這樣的結構:
Object {index.php: Object, upload.php:Object}
index.php: Object
0: Array(3)
0: "Home"
1: "read"
2: "index.php"
10: Array(3)
0: "Updates"
1: "update_core"
2: "update-core.php"
upload.php: Object
5: Array(3)
0: "Library"
1: "upload_files"
2: "upload.php"
10: Array(3)
0: "Add New"
1: "upload_files"
2: "media-new.php"
這是輸出的一個例子縮短只給你一個想法。因此它包含一個包含2個對象的對象,而這2個對象每個包含2個數組(這2個對象名稱是與相關頂級菜單項匹配的索引值,而數組中的值是子屬性菜單項)。
所以在Javascript中我有一個循環收集這些對象名稱,即index.php文件和upload.php的,然後我有一個循環採集到的對象的子菜單的屬性裏面一個循環:
$('#admin-menu-manager > li > ul').each(function(index) {
//this gets the object name e.g. index.php or upload.php
var associatedTopLevelMenuItemLabel = $(this).parent().find('.menu-url').val();
var $this = $(this);
var $subLevelUl = $(this).find("li");
$($subLevelUl).each(function(index) {
//these below variables get the properties of the sub menu
//menu item property 1
var subLevelMenuItemLabel = $(this).find('.menu-label').val();
//menu item property 2
var subLevelMenuItemCapability = $(this).find('.menu-capability').val();
//menu item property 3
var subLevelMenuItemLink = $(this).find('.menu-url').val();
//now I am creating an array to store the sub level properties
var subLevelMenuItemArray = [subLevelMenuItemLabel, subLevelMenuItemCapability, subLevelMenuItemLink];
});
});
這段代碼的問題是: 一)我不知道如何創建一個使用變量「associatedTopLevelMenuItemLabel」,因爲它的名字的對象,而且, b)我不知道如何把這些「 subLevelMenuItemArray'數組放入對象中。
我知道如何將數組推入另一個數組,但我相信您不能將數組推送到此對象中。我試圖做甚至可能在Javascript中,或者我在這裏吠叫錯誤的樹,我應該使用PHP?
** JavaScript對象**它只是一個* hashset * https://www.w3schools.com/js/js_objects.asp – 2017-05-29 05:59:35
嗨anete.anetes感謝您的評論,你是說我不需要擔心實際創建對象和數組我只需要創建一個看起來像是對象和數組的字符串?我很抱歉,我不熟悉哈希集,我仍然在學習。但我認爲你所說的話是有道理的。因爲我實際上並不需要利用javascript對象和數組的功能,所以我只需要讓它看起來像我想的那樣。 – user1190132
是的,你可以通過字符串'object ['propname']'來訪問你的對象的屬性,並且你可以將'propname'存儲在某個變量的內部 – 2017-05-29 06:03:36