2017-08-14 98 views
1

我需要在我的functions.php文件中觸發一個鉤子後運行腳本。即時通訊使用WordPress的mailchimp插件,我需要做一些文字插入和display = "none"等,在html:在functions.php中執行document.ready

add_action('mc4wp_form_success', function() { 
    // do something 
    echo '<script type="text/javascript">', 
     'console.log("starting....");', // this works 
    'document.getElementById("mailchimp-is-subscribed").style.display = "none";', 
     'document.getElementById("mailchimp-success-form").style.display = "block";', 
     'console.log("end");', 
    '</script>'; 
}); 

我得到的錯誤是stylenull。我假定文件沒有準備好? $不起作用。 我做錯了嗎?我需要在調用該鉤子後運行該代碼。將代碼放在.js文件中效果很好。由於

+0

事實上,你這樣做是不對的。你不能像這樣混淆PHP和JavaScript。 –

+0

@NiettheDarkAbsol是的,我認爲是的。什麼是正確的方法呢? – Sylar

回答

0

您可以在DOMContentLoaded事件添加代碼爲:

document.addEventListener('DOMContentLoaded', function() { ..your_code... }, false);

檢查這個答案:pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

+0

對不起,但看起來像jquery的一半,我不能在那裏使用jQuery。 – Sylar

+0

對不起,你是對的!我已經改變了答案。 – Fredster

+1

SWEET!很好用,但採用這種格式'document.getElementById(「mailchimp-is-subscribed」)。style.display =「none」;'謝謝! – Sylar

相關問題