使用“if/else"使用 OnClick [英] Using "if/else" with OnClick

查看:36
本文介绍了使用“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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆