简体   繁体   中英

How to reload a JavaScript of a page without reloading the page (Vanilla JS)

I have nested fields that are being appended to the DOM when a user wants to add more fields. this is being done by a nested_fields.js file.

The issue is one of the fields being appended is a calender field that is being handled by another JS file called calender_manager.js

calender_manager.js is using the Flatpickr module and it looks for input tags with the.flatpickr class in the HTML file of the page. This happens when the page is loaded so the fields appended to the DOM by nested_fields.js with the.flatpickr class don't get picked up by calender_manager.js.

So far my solution is to make one custom JS file for the nested calendar fields that handles appending the nested fields and adding flatpickr. I was wondering if there is a better way.

I've never heard of flatpickr but I just looked into it, maybe I don't know what you are asking, but are you trying to get it to enable after the page loads? If so calling flatpickr(".my_input"); again works.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<input type="text" class="my_input" /><br />
<input type="button" id="enable" value="Click to enable flatpickr" />
<input type="button" id="disable" value="Click to disable flatpickr" />

<script>
var f;
document.querySelector("#enable").onclick = function () {
    f = flatpickr(".my_input");
}
document.querySelector("#disable").onclick = function () {
    f.destroy();
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM