javascript - 如何将 Html 框与 Javascript 函数链接起来以给出预期的输出?

标签 javascript html

我正在尝试将输入框与 id="b" 链接(位于内部div id="but1" .) 使用 JS 函数,给出所需的输出(仅在数组内计数)..但是我的初级逻辑在代码中没有发现任何问题,我犯了什么错误?

这是我第二次重写所有的 JS 函数,但我似乎仍然找不到问题所在。

function alert1() {

  let arr = [];
  arr.value = document.getElementById('a');
  let b = document.getElementById('b');
  b.value;

  for (let i = 0; i < arr.length; i++) {
    if (arr[i].length <= 10) {
      console.log(arr[i].length + " ", "Mbaroi rasti 1");
      b.value = "Mbaroi rasti 1";
      return b;
    } else if (arr[i].length >= 11 && arr[i].length <= 12) {
      console.log(arr[i].length + " ", "Mbaroi rasti 2");
      b.value = "Mbaroi rasti 2";
      return b;
    } else if (arr[i].length >= 13) {
      console.log(arr[i].length + " ", "Mbaroi rasti 3");
      b.value = "Mbaroi rasti 3";
      return b;
    }
  }
}

alert1();
<body>

  <div id="div1" style="text-align:center;">
    <div id="but1">
      <button id="button_1" onclick="document.getElementById('b').innerHTML=alert1()">Calc_bashkesia-1</button>
      <label><b>InputBox</b></label>
      <input type="text" id="a" placeholder="Enter Some Input" />
      <input type="text" id="b" placeholder="Calculation output here" for="a" />
    </div>
  </div>

</body>

我希望 id="button_1"的按钮在 id="b"的输入框中输出alert1()回调的计算结果,但这并没有发生。

最佳答案

更改 HTML 中的 onclick 以调用您的函数。

也不需要数组或 for 循环。

我留在里面的返回没有做任何事情。

function alert1 () {

const aValue = document.getElementById('a').value;
const b = document.getElementById('b');

if(aValue <= 10) {
    console.log(aValue +" ", "Mbaroi rasti 1");
    b.value = "Mbaroi rasti 1";
    return b;
} else if(aValue >= 11 && aValue <= 12) {
    console.log(aValue +" ", "Mbaroi rasti 2");
    b.value = "Mbaroi rasti 2";
    return b;
} else if(aValue >= 13) {
    console.log(aValue +" ", "Mbaroi rasti 3");
    b.value = "Mbaroi rasti 3";
    return b;
}
   
}
<div id="div1" style="text-align:center;">
    <div id="but1">
        <button id="button_1" onclick="alert1()">Calc_bashkesia-1</button>
        <label><b>InputBox</b></label>
        <input type="text" id="a" placeholder="Enter Some Input"/>
        <input type="text" id="b" placeholder="Calculation output here" for="a"/>
    </div>
</div>

关于javascript - 如何将 Html 框与 Javascript 函数链接起来以给出预期的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57465420/

相关文章:

javascript - 在 onEachFeature 传单之外调用函数

javascript - TypeError : this. props.nextStep 不是函数 React 错误

java - 如何使用phonegap插件从android调用javascript函数

HTML CSS 如何去掉滚动条让网站全屏?

javascript - 如何修改所选选项文本并在下一个选项后恢复文本

html - IE 中的边框看起来比 Chrome 中的边框粗

javascript - Cordova 对话框插件不起作用

javascript - 多个嵌套的ng-repeat-start无法显示数据

javascript - 更改文本区域中唯一单词的样式/颜色?不是除法

html - 侧面倾斜的形状(响应)