Javascript function does not start if browser does it quickly

Asked 1 years ago, Updated 1 years ago, 23 views


at the site you are building with Javascript I would like to ask you a question because I do not know the cause.

List the table data in your browser and
If you change the value in the pull-down selection,
Launch the live function and perform the data update process
As for how it works, if you pull down quickly, the live function is
Data updates are leaked without booting.
If you operate it slowly, it will start without any problems.
Also, this phenomenon varies from browser to browser and
FireFox, IE, not Chrome.

I don't know the cause because the event happens at random.
Is there any possible reason?
Please let me know if you know.

Environment
·jquery-1.6.2
·Web server: Apache
·DB: MySQL

javascript

2022-09-30 13:56

1 Answers

The answer is Esper, but I interpreted the question with a strong imagination.

  • JavaScript functionality does not work when you operate the pulldown menu that has JavaScript functionality immediately after the page is displayed.

'use strict';
document.addEventListener('DOMContentLoaded', function(event){
  event.target.querySelectorAll('#sampleselect').forEach(function(select){
    select.addEventListener('change', function(event){
      console.log(event.target.value);
    }, false);
  });
}, false);
<p>(...huge amount of content...)</p>

<form id="sample">
  <p>
    <select name="alphabet">
      <option>A</option>
      <option>B</option>
      <option>C</option>
      <option>D</option>
    </select>
  </p>
  <p>
    <select name="number">
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
    </select>
  </p>
</form>

<p>(...huge amount of content...)</p>

Wait for the previous code to run until DOMContentLoaded.
Therefore, JavaScript functionality may not work until DOMContentLoaded fires, and the output to console.log may not work if you select a select element immediately after viewing a web page.
JavaScript DOM references work only after DOM is built, so DOM construction needs to be done first.
Therefore, static HTML+JavaScript is not fully compatible with the operation immediately after display.

There are two main countermeasures.

  • Unable to operate until JavaScript features are applied
  • Generate Element Nodes in JavaScript

The former gives the element the disabled attribute to create an inoperable situation.
The latter dynamically generates nodes with APIs such as createElement, defines the event, and inserts the node to accommodate the immediate action.

Re:@hosayu


2022-09-30 13:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.