如何在页面上的 div 部分加载后执行 JavaScript?仅使用标准 JavaScript。
这是有问题的 div 部分,摘自 (https://hera-warm-demo.mybigcommerce.com/checkout):
<div aria-busy="false" class="checkout-view-content checkout-view-content-enter-done">
<div class="loading-skeleton">
<div>
<form class="checkout-form" data-test="payment-form" novalidate="">
<fieldset class="form-fieldset">
<div class="form-body">
<ul class="form-checklist optimizedCheckout-form-checklist">
<li class="form-checklist-item optimizedCheckout-form-checklist-item form-checklist-item--selected optimizedCheckout-form-checklist-item--selected">
<div class="form-checklist-header form-checklist-header--selected">
<div class="form-field">
<label for="radio-bigpaypay" class="form-label optimizedCheckout-form-label">
<div class="paymentProviderHeader-container">
<div class="paymentProviderHeader-nameContainer" data-test="payment-method-bigpaypay">
<div aria-level="6" class="paymentProviderHeader-name" data-test="payment-method-name" role="heading">Test Payment Provider</div>
</div>
<div class="paymentProviderHeader-cc">
<ul class="creditCardTypes-list"></ul>
</div>
</div>
</label>
</div>
</div>
</li>
</ul>
</div>
</fieldset>
</form>
</div>
</div>
</div>
此部分是页面上的最后一部分,仅当客户单击上一部分中的“继续”按钮时才会加载。
这是我尝试过的代码,但不起作用..我期望 JavaScript 在加载“loading-骨骼”div 后执行。
请注意,我无法将脚本包含在动态加载的 HTML 标记中,我只能注入 JavaScript 代码。
<script>
document.getElementsByClassName("checkout-view-content").addEventListener("DOMContentLoaded", (event) => {
document.querySelector('label[for="radio-bigpaypay"] .paymentProviderHeader-cc').style.visibility = "hidden";
});
</script>
这是一个纯 CSS 答案,表明您可以更改可见性而无需 JavaScript。我的答案确实包含 javascript,只是为了表明 CSS 仍然适用于动态元素。
label[for="radio-bigpaypay"] .paymentProviderHeader-cc{visibility:hidden}
const results = document.querySelector("#results");
results.innerHTML = `<div aria-busy="false" class="checkout-view-content checkout-view-content-enter-done">
<div class="loading-skeleton">
<div>
<form class="checkout-form" data-test="payment-form" novalidate="">
<fieldset class="form-fieldset">
<div class="form-body">
<ul class="form-checklist optimizedCheckout-form-checklist">
<li class="form-checklist-item optimizedCheckout-form-checklist-item form-checklist-item--selected optimizedCheckout-form-checklist-item--selected">
<div class="form-checklist-header form-checklist-header--selected">
<div class="form-field">
<label for="radio-bigpaypay" class="form-label optimizedCheckout-form-label">
<div class="paymentProviderHeader-container">
<div class="paymentProviderHeader-nameContainer" data-test="payment-method-bigpaypay">
<div aria-level="6" class="paymentProviderHeader-name" data-test="payment-method-name" role="heading">Test Payment Provider</div>
</div>
<div class="paymentProviderHeader-cc">
HIDE ME
<ul class="creditCardTypes-list"></ul>
</div>
</div>
</label>
</div>
</div>
</li>
</ul>
</div>
</fieldset>
</form>
</div>
</div>
</div>`;
label[for="radio-bigpaypay"] .paymentProviderHeader-cc{visibility:hidden}
<div id="results"></div>