简体   繁体   中英

Strange behavior of Chrome browser with Javascript

I heve some code line. Why Mozilla Firefox take first saveImage() properly and Chrome take second saveImage. Even if console.log($('#param-form').size()) = 0 ??? I use Jquery 1.7.2. with length instead size() it's the same result.

$(document).ready(function(){ 
   if ($('#catalog-image-form').size()) {
       function saveImage() {
           some logic 1
       } 
   }

   if ($('#param-form').size()) {
      function saveImage() {
         some logic 2 
      }
   }
});

也许功能提升存在问题?

Beside what +Jaroslaw said about the .size() method being deprecated as jQuery 1.8, have you tried this?

if ($('#param-form').size() > 0)

You test 2 different selectors, are you sure Chrome does not execute both saveImage() ?

At script loading, Chrome should search all global function declaration to optimize/pre-compile the code inside, in order of declaration.

If you declare the function at the runtime, using = function , the declaration is done only if the line is executed.

So, in your case, define the function at runtime with saveImage = function () {…} .

 $(document).ready(function(){ if ($('#catalog-image-form').size()) { saveImage = function () { $("#input1").val("some logic 1"); } function globalfunction () { $("#input1").val("some logic 1"); } } if ($('#param-form').size()) { saveImage = function () { $("#input1").val("some logic 2"); } function globalfunction () { $("#input2").val("some logic 2"); } } if (false) { saveImage = function () { $("#input1").val("some logic 3"); } function globalfunction () { $("#input2").val("some logic 3"); } } saveImage(); globalfunction(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <form id="catalog-image-form"> <input type="text" name="input1" id="input1"/> <input type="text" name="input2" id="input2"/> </form> 

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