You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

调用函数时updateb与updatec未定义的技术求助

解决函数未定义问题:updateb/updatec提示未定义,updatea正常运行

看起来你的问题核心是JavaScript作用域导致的函数访问不到,我来帮你拆解一下:

问题根源

你应该是把updatebupdatec定义在了$(document).ready()的回调函数内部,而updatea要么是定义在了全局作用域,要么被意外挂载到了全局。在ready回调里定义的函数默认是局部作用域,外部(比如HTML的点击事件、全局脚本调用)根本访问不到,所以会报"未定义"错误。

两种可行解决方案

方案1:把函数挂载到全局作用域(推荐)

如果你的函数依赖DOM加载完成后才能正常工作(比如操作页面元素),最好保留在ready回调里定义,然后手动挂载到window对象(全局作用域):

$(document).ready(function() {
  // 你的$.get请求代码
  $.get('php/beacon.php', function(response) {
    console.log(response);
    response.forEach(function(item, index) {
      console.log(item);
      $(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
    });
  });

  // 定义你的三个函数
  function updatea() {
    // 你的updatea完整逻辑
    $('td.coloured').css('background-color', 'transparent').removeClass('coloured');
    // ...其他代码
  }

  function updateb() {
    // 你的updateb逻辑
    // 比如重新获取数据更新表格
    $.get('php/beacon.php', function(response) {
      response.forEach(function(item) {
        $(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
      });
    });
  }

  function updatec() {
    // 先调用updateb,再调用updatea
    updateb();
    updatea();
  }

  // 关键:把函数挂载到全局,让外部能访问
  window.updatea = updatea;
  window.updateb = updateb;
  window.updatec = updatec;
});

方案2:直接把函数定义在全局作用域

如果你的函数不依赖DOM加载状态,可以直接把函数写在$(document).ready()外面,这样默认就是全局可用的:

// 全局定义函数
function updatea() {
  // 你的updatea完整逻辑
  $('td.coloured').css('background-color', 'transparent').removeClass('coloured');
  // ...其他代码
}

function updateb() {
  // 你的updateb逻辑
  $.get('php/beacon.php', function(response) {
    response.forEach(function(item) {
      $(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
    });
  });
}

function updatec() {
  updateb();
  updatea();
}

$(document).ready(function() {
  // 你的$.get初始化代码
  $.get('php/beacon.php', function(response) {
    console.log(response);
    response.forEach(function(item, index) {
      console.log(item);
      $(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
    });
  });
});

额外检查点

  1. 确保函数定义没有语法错误:比如有没有漏掉闭合的}或者);,语法错误会导致函数无法正常定义。
  2. 如果是通过HTML事件调用(比如<button onclick="updatec()">),要确保函数已经被挂载到全局后再触发(也就是ready回调执行完成后)。

内容的提问来源于stack exchange,提问作者Avalon Parkes-barton

火山引擎 最新活动