简体   繁体   中英

Update div only if a certain conditions holds true

I am writing a simple webserver with micropython. I want to switch on a relay for a certain duration (given in input by the user from the HTML form). When the relay is off, I display a div with the input form for the duration and the activation button. When the relay is on, the same div is replaced with a countdown; when the relay is on I want to refresh the div every second so that the countdown is updated. When the relay is off, I don't want the div to update because otherwise, if you try to input the duration, every second the input number in the box is cleared.

My div is updated by the following script:

  <script>
    $(document).ready(function () {
      setInterval(function () {
       
        $("#div_name").load(window.location.href + " #heatingDiv");
        
      }, 1000);
    });
  </script>

The div is:

  <div id="div_name">
    <h1>Title</h1>
    insert_content
  </div>

The keyword "insert_content" is replaced with the HTML code inside the micropython program (accordingly to the relay state) before the HTML response is sent.

With the previous code everything works fine except for the fact that the div is updated every second even when the relay is off, making it impossible to input the duration in the form.

What I'd like to do is passing an argument to the script similarly as when one uses onClick to call it (I can modify "state" within micropython before sending the response):

  <div id="div_name(state)">
    <h1>Title</h1>
    insert_content
  </div>

and the script should look like:

  <script>
    $(document).ready(function () {
      setInterval(function (var state) {
        
        if(state){
        $("#div_name").load(window.location.href + " #heatingDiv");
        }
        
      }, 1000);
    });
  </script>

Of course this does not work because id=div_name is not a function call: it is just to give an idea of what I'd like to achieve. How can I do that?

Why not use a data attribute:

 const $div = $("#div_name"); const state = $div.data('state'); if (state) { setInterval(function() { $div.load(window.location.href + " #heatingDiv"); }, 1000); } // if you are wanting to do the interval to check if the state changes, you could change it around setInterval(function() { const state = $div.data('state'); if (state) { $div.load(window.location.href + " #heatingDiv"); } }, 1000);
 <div id="div_name" data-state="state"> <h1>Title</h1> insert_content </div>

Perhaps if you are only wanting to run the load when the state changes, you may be better of with a MutationObserver watching the data attribute instead of a timeout

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