dacongyun.com
分享国内外服务器主机优惠信息

js折腾头要炸了

  1. for (i = 0; i < $(“.newBarcode”).length; i++) {
  2.     var bc = $(“.newBarcode”)[i].value;
  3.         var ii = $(“input.newBarcode”)[i].id.replace(/[^0-9]/ig,””);
  4.         var regString = /[a-zA-Z]+/;
  5.         if (!regString.test(bc)) {
  6.                 $.getJSON(“http://192.168.0.240/location.php?barcode=” + bc,function(data){
  7.                         if (!data.location) {
  8.                                 console.log(ii);
  9.                                 if ($(“#prodInfoName” + ii)[0].style.length < 2) {
  10.                                         $(“#prodInfoName” + ii).css(‘color’,’red’).css(‘font-weight’,’bold’);
  11.                                 }
  12.                         }
  13.                 });
  14.         }
  15. }

复制代码

如果去掉for命令 是没问题 可以执行

但是加入for命令console.log(ii); 输出都为  $(“.newBarcode”).length -1 的值

到底哪里问题

如果是console.log(ii) 放到getJSON之前是可以输出每个 ii 值说来 这个又是没问题  到底是哪里出问了

网友回复:

注册 作用域问题吧 试下for (let i = 0; i < $(“.newBarcode”).length; i++)

新网络 因为getJSON是异步的,换句话说,就是他有可能会在你整个for执行完毕后再慢悠悠的进行网络连接,执行里面的内容。所有你需要改成同步执行,把你的代码放到下面这两行之间就行。 $.ajaxSettings.async = false; …….. $.ajaxSettings.async = true;

x1184 异步问题 for 它不等你 get 某个url的,它自己for 完了,值已经是lenth-1了, 然后你第一个barcode才收到了,于是console.log出来的,就是lenth-1。

u2u 看了下确实异步问题 但强制改同步感觉对性能很影响

逸笙 。。$.getJSON 是异步ajax   你可以把ii作为参数放进ajax函数 然后用回调的时候用 this.参数名 取出来

x1184 原来是这样,谢谢大佬

ghs9262 那我来说个菜鸟的解决方案: for (i) {     bc=xxxxx;     ii=xxxxx;     if (xxxx) barcode(bc, ii); } function barcode(a, b) { getJSON(xxxxxxx); xxxxxxxxxxxx }

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

真正的个人支付接口

云免签H5支付