我正在爲自己的用法開發一個插件,並且我想擺脫出現在頂部的所有惱人的wordpress消息,包括更新,錯誤,信息等。鑑於顯而易見的事實該插件的菜單頁面是由PHP生成,我試圖消除與根據我的研究,一個PHP代碼,這些消息是這樣的:刪除父母和所有子元素不工作
function remove_core_updates(){
global $wp_version;return(object) array('last_checked'=> time(),'version_checked'=> $wp_version,);
}
add_filter('pre_site_transient_update_core','remove_core_updates');
add_filter('pre_site_transient_update_plugins','remove_core_updates');
add_filter('pre_site_transient_update_themes','remove_core_updates');
我說這個我插件的PHP文件的頂部,應刪除通知,但仍然出現一些插件的錯誤消息。除此之外,上面的代碼將刪除我在儀表板中訪問的所有菜單頁的更新通知。這我不想要。
作爲一種變通方法,我寫了一個函數,它做什麼,我想:
function remove_wp_messages(selector) {
var child = document.querySelector(selector),
parent = child.parentNode,
index = Array.prototype.indexOf.call(parent.children, child);
for (var i = 1; i < Number(index + 1); i++) {
var elements = document.querySelector("#wpbody-content > :nth-child(" + i + ")");
while (elements.firstChild) {
elements.removeChild(elements.firstChild);
elements.style.display = "none";
}
}
}
window.onload = remove_wp_messages("#wpbody-content > link");
鑑於第一個HTML元素我添加到菜單頁面是link
到外部樣式表,在javascript函數在returns
以上的那個link
的索引並且從元素直到link
,因此循環移除所有子節點。問題在於,我不僅要刪除子元素,還要刪除父母,這相當於刪除我的插件內容以上的通知。我試圖取代:
elements.style.display = "none";
有了這個:
elements.remove();
沒有運氣。我不明白的是,父元素被隱藏起來,但我用remove()
替換它,它刪除了我的內容而不是通知。爲什麼?我打開php和javascript的建議。
SOLUTION
據@PetrSr答案,我的代碼現在看起來像這樣:
function remove_wp_messages(selector) {
var child = document.querySelector(selector),
parent = child.parentNode,
index = Array.prototype.indexOf.call(parent.children, child);
for (var i = Number(index); i > 0; i--) {
document.querySelector("#wpbody-content > :nth-child(" + i + ")").remove();
}
}
非常簡單。
這個技巧!我的做法完全不合邏輯。 –
'Number(index)'必須爲'Number(index);'後面使用逗號而不是分號; –