Using quot;if/elsequot; with OnClick(使用“if/else使用 OnClick)
问题描述
首先,是否可以直接在html中使用onclick属性编写if/else语句?如果是这样,为什么我的代码不起作用?
First of all, is it even possible to write if/else statements directly in html with onclick attribute? And if so, why is my code not working?
所以这是一个按钮.Calc.Input.value"指的是文本输入,如果该字段为 0 或空白,我想显示错误消息.如您所见,在所有其他情况下,我希望发生其他一些事情.不过,这无关紧要,因为else"之后的所有内容之前都运行良好.
So this is a button. The "Calc.Input.value" refers to a text input and I want to display an error message if that field is 0 or blank. In all other cases I want some other things to happen as you can see. This is not relevant though, as everything after the "else" worked fine before.
<INPUT TYPE="button" NAME="drop" id="dropbutton" style="background-color:#D1E8D5;" VALUE="
Släpp ankare " OnClick="if ("Calc.Input.value == ''" || "Calc.Input.value == '0'")
{window.alert("Please enter a number");} else
{document.getElementById('dropbutton').value=' Justera
längd ';document.getElementById('length').innerHTML =
Calc.Input.value;document.getElementById('dropbutton').style.cssText = 'background-
color:#FFF6B3;';}">
推荐答案
不要把它放在onclick属性中.
Just DON'T put it in the onclick attribute.
使用
<INPUT TYPE="button" NAME="drop" id="dropbutton" style="background-color:#D1E8D5;" VALUE="Släpp ankare ">
<script>
document.getElementById('dropbutton').onclick = function() {
if (Calc.Input.value == '' || Calc.Input.value == '0') {
window.alert("Please enter a number");
} else {
document.getElementById('dropbutton').value=' Justera längd ';
document.getElementById('length').innerHTML = Calc.Input.value;
document.getElementById('dropbutton').style.backgroundColor = '#FFF6B3';
}
return false;
}
</script>
这篇关于使用“if/else"使用 OnClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用“if/else"使用 OnClick


基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01