javascript 已声明函数,但从未读取其值

wgx48brx  于 2023-02-28  发布在  Java
关注(0)|答案(2)|浏览(955)

该函数在HTML页面上工作,但不在外部JS文件中工作,并显示此错误(声明了"checkSelection",但从未读取其值)。是否有任何解决方案?

function checkSelection(that) {
    if (that.value == "web-dev") {
      document.getElementById("web-section").style.display = "block";
    } else {
      document.getElementById("web-section").style.display = "none";
    }
    if (that.value == "grp-dsg") {
      document.getElementById("graphic-section").style.display = "block";
    } else {
      document.getElementById("graphic-section").style.display = "none";
    }
    if (that.value == "dgt-mkt") {
      document.getElementById("marketing-section").style.display = "block";
    } else {
      document.getElementById("marketing-section").style.display = "none";
    }
  }
<input onchange="checkSelection(this);">
tsm1rwdh

tsm1rwdh1#

这是IDE中的TypeScript检查器报告的错误。若要消除该错误,可以使用以下解决方法:

window.checkSelection = function(that) {
    if (that.value == "web-dev") {
      document.getElementById("web-section").style.display = "block";
    } else {
      document.getElementById("web-section").style.display = "none";
    }
    if (that.value == "grp-dsg") {
      document.getElementById("graphic-section").style.display = "block";
    } else {
      document.getElementById("graphic-section").style.display = "none";
    }
    if (that.value == "dgt-mkt") {
      document.getElementById("marketing-section").style.display = "block";
    } else {
      document.getElementById("marketing-section").style.display = "none";
    }
  }

基本的问题是使用内联事件监听器,这被广泛认为是不好的做法,相反,我建议您将该输入指定为id并使用addEventListener

document.getElementById('section-picker').addEventListener('change', function() {
    if (this.value == "web-dev") {
      document.getElementById("web-section").style.display = "block";
    } else {
      document.getElementById("web-section").style.display = "none";
    }
    if (this.value == "grp-dsg") {
      document.getElementById("graphic-section").style.display = "block";
    } else {
      document.getElementById("graphic-section").style.display = "none";
    }
    if (this.value == "dgt-mkt") {
      document.getElementById("marketing-section").style.display = "block";
    } else {
      document.getElementById("marketing-section").style.display = "none";
    }
  });

如果你接受这个建议,你需要确保Javascript在页面中的input被解析 * 之后 * 执行,最简单的方法是在script标签中应用defer属性。

py49o6xq

py49o6xq2#

在函数中使用输入之前,需要先侦听输入

let number = document.querySelector('input');

function check(that){
  if(that.value == 1){
    console.log('hello');
   }
   else{
    console.log('bye');
   }
 }
 
 number.addEventListener('input', ()=>{
  check(number);
 });
<input type="number">

以这个为例,你把输入赋值给一个变量,然后每当这个数改变时,你就运行这个函数来检查值并显示结果。2复选框也是一样。

相关问题