我在外部 Javascript 文件中有一段代码,它向所有带有接受复选框的 Contact Form 7 表单添加了一个工具提示。
如果在超时内则有效;
jQuery(document).ready(function($) {
setTimeout(() => {
$('.wpcf7-submit[disabled]').after('<div class="wpcf7-tooltip">Check the consent field to continue</div>');
}, "2000");
});
但是没有的话就无法工作。
jQuery(document).ready(function($) {
$('.wpcf7-submit[disabled]').after('<div class="wpcf7-tooltip">Check the consent field to continue</div>');
});
此 Javascript 文件是在联系表单 7 Javascript 依赖项(CF7 Recaptcha 除外)之后加载的。
知道为什么以及如何在不超时的情况下解决这个问题吗? - 并不是说将它包装在这个函数中是一个问题,但它不优雅,我想知道如何跟踪和解决这个问题。
如果您控制创建表单的代码,您可以让它触发一些事件来通知您它已被创建。
否则,您可以设置
MutationObserver
而不是轮询该节点的 DOM。
jQuery(document).ready(function($) {
const body = document.body;
function tryToAppendToSubmit() {
const submitButton = $('.wpcf7-submit[disabled]');
if (submitButton.length) {
submitButton.after('<div class="wpcf7-tooltip">Check the consent field to continue</div>');
return true;
}
return false;
}
document.getElementById("btn").addEventListener("click", () => {
$(body).append(`<input class="wpcf7-submit" disabled />`)
})
// Check if it exists (it won't exist in this case but it could
// in your example?
if (tryToAppendToSubmit()) {
return;
}
const callback = function(mutationsList, observer) {
// Checking both for additions or modifications
for (const mutation of mutationsList) {
if (mutation.type === 'attributes' && mutation.attributeName === 'disabled') {
// Check if the modified element has the specified class
if (mutation.target.classList.contains('wpcf7-submit')) {
console.log('.wpcf7-submit[disabled] detected!');
tryToAppendToSubmit()
// Stop observing once the change is detected
observer.disconnect();
}
}
// Check for new elements being added
else if (mutation.type === 'childList') {
for (const addedNode of mutation.addedNodes) {
if (addedNode.nodeType === 1 && addedNode.classList.contains('wpcf7-submit')) {
console.log('.wpcf7-submit element added!');
tryToAppendToSubmit()
// Stop observing once the change is detected
observer.disconnect();
}
}
}
}
};
const observer = new MutationObserver(callback);
observer.observe(body, {
attributes: true,
subtree: true,
childList: true
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<button id="btn">Click me to add form and see the checkbox be added</button>