八、JavaScript运算符

八、JavaScript运算符
运算符“=”用于赋值
运算符“+”用于加值

例如:指定变量值,将其值相加。

<!DOCTYPE html>
<html>
<body>
<p>点击按钮计算 x.</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction()
{
y=5;
z=2;
x=y+z;
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>

1、字符串“+”运算符
用于把文本值或字符串变量连接起来,例如:

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction()
{
txt1="我是字符串的";
txt2="连接符号";
txt3=txt1+txt2;
document.getElementById("demo").innerHTML=txt3;
}
</script>
</body>
</html>

2、使用字符串添加空格,例如:

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction()
{
txt1="我是字符串的";
txt2="连接符号";
txt3=txt1+" "+txt2;
document.getElementById("demo").innerHTML=txt3;
}
</script>
</body>
</html>

3、字符串跟数字拼接
两个数字相加,返回数字相加的和;如果数字与字符串相加,返回字符串。例如:

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x=5+8;
var y="5"+6;
var z="Hello"+1;
var demoP=document.getElementById("demo");
demoP.innerHTML=x + "<br>" + y + "<br>" + z;
}
</script>
</body>
</html>

九、JavaScript比较

1、可以使用条件语句中使用比较运算符对值进行比较,然后根据结果采取行动。例如:
if(age < 18) x = “太小”;

代码实例:

<!DOCTYPE html>
<html>
<body>
<p>点击按钮检测年龄。</p>
年龄:<input id="age" value="18" />
<p>是否达到投票年龄?</p>
<button onclick="myFunction()">点击按钮</button>
<p id="demo"></p>
<script>
function myFunction()
{
    var age,voteable;
    age=document.getElementById("age").value;
    voteable=(age<18)?"年龄太小":"年龄已达到";
    document.getElementById("demo").innerHTML=voteable;
}
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值