![](/img/trans.png)
[英]Remove class from all child elements and add class on parent/parent of clicked Jquery
[英]Remove parent and all child elements not working
我正在開發自己的插件,我想擺脫顯示在頂部的所有煩人的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
外部樣式表的link
,因此上面的javascript函數 returns
該link
的索引,並從元素中刪除所有子節點,直到link
為止,從而刪除了循環 。 這是問題所在,我不僅要刪除子元素,還希望刪除父元素,這等同於刪除插件內容上方的通知。 我嘗試更換:
elements.style.display = "none";
有了這個:
elements.remove();
沒運氣。 我不明白的是,父元素被隱藏了,但是我用remove()
替換了它,它刪除了我的內容而不是通知。 為什么? 我願意接受php和javascript的建議。
解
根據@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();
}
}
非常簡單。
像這樣向后循環遍歷元素可以解決您的問題:
for (var i = Number(index); i > 0; i--) {
//your code
}
刪除DOM元素時,您無法向前循環,因為在刪除element1之后,element2成為第一個元素。 如果然后刪除第二個元素,則實際上是在刪除原來的element3。 等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.