如何计算innerHTML内部的变量? [英] Howto count a variable inside of innerHTML?

查看:205
本文介绍了如何计算innerHTML内部的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算一个innerHTML内部的变量?

How is it possible to count a variable inside of a innerHTML?

JS

var counter = 1;
counter++;
alert(counter);

$(".end").html('Test ' + counter+1 + ' Test');

HTML

<p class="end"></p>

在我的 JSfiddle 示例中,它适用于警报示例,但不适用于innerHTML元素.为什么?怎么上班?

In my JSfiddle example, it works for alert example, but not in the innerHTML element. Why? How is it getting work?

推荐答案

这是因为您正在进行字符串连接.

Its because you are doing string concatenation.

当前评估

'Test ' + counter+1 + ' Test'
'Test 2' +1 + ' Test'
'Test 21' + ' Test'
'Test 21 Test'

您应该将计算内容包装为()

You should wrap your calcualtion insde ()

$(".end").html('Test ' + (counter+1) + ' Test');

添加()时,它具有更高的优先级并在表达式中首先计算.

When you add () that takes higher precedence and calculates first in the expression.

当前评估

'Test ' + (counter+1) + ' Test'
'Test ' + 3 + ' Test'
'Test 3' + ' Test'
'Test 3 Test'

这篇关于如何计算innerHTML内部的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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