javascript - 突出显示 JavaScript 函数结果?我创建了一个功能来突出显示要突出显示的特定区域,但它没有突出显示?
问题描述
我创建了一个函数,旨在突出显示函数结果的特定元素。它是我正在构建的单利计算器的一部分,我创建了一个单独的函数来向特定元素添加一个类,然后我在结果中调用了该函数,该函数应该显示在浏览器上,但它似乎没有突出显示它。
我复制了一段 JS、CSS 和 HTML:
function highlight_p() {
var element = document.getElementById("principal");
element.classList.add("highlight");
}
function compute() {
// Ensure all values are _numbers_
p = Number(document.getElementById("principal").value);
r = Number(document.getElementById("myRange").value);
n = Number(document.getElementById("years").value);
const newDate = new Date();
newDate.setFullYear(newDate.getFullYear() + n);
let result = "If you deposit " + highlight_(p) + ", " + "<br>";
result += "at an interest rate of " + r + "%," + "<br>";
result += "you will receive an amount of " + getFutureValue(p, r, n).toFixed(2) + "," + "<br>";
result += "in the year " + (newDate.getFullYear());
showResult(result);
}
.highlight {
background-color: yellow;
}
<button onclick="compute()">Compute Interest</button>
<p id="result" onsubmit="hightlight_p()"></p>
<p id="result"></p>
<p id="result"></p>
<p id="result"></p>
解决方案
- ID 必须是唯一的
- ps没有onsubmit事件
- 你没有
showResult
或getFutureValue
任何地方 - 你没有任何东西
id="principal"
highlight_(p)
不是有效的 JS
也许你是这个意思?
const highlight = str => `<span class="highlight">${str}</span>`;
const currency = num => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(num);
const getFutureValue = (principal,rate,year) => {
var interest = rate/100+1;
return currency(principal*Math.pow(interest,year))
}
document.getElementById("compute").addEventListener("click",function() {
// Ensure all values are _numbers_
p = +document.getElementById("principal").value;
r = +document.getElementById("rate").value;
n = +document.getElementById("years").value;
const newDate = new Date();
newDate.setFullYear(newDate.getFullYear() + n);
document.getElementById("result").innerHTML = `If you deposit ${highlight(currency(p))} at an interest rate of ${highlight(r+"%")},<br>
you will receive an amount of ${highlight(getFutureValue(p, r, n))} in the year ${highlight(newDate.getFullYear())}`;
})
.highlight {
background-color: yellow;
}
#rate, #years { width:50px }
$<input type="number" id="principal" /> at <input type="number" id="rate" />% for <input type="number" id="years" /> years
<button id="compute">Compute Interest</button>
<p id="result"></p>
推荐阅读
- elasticsearch - Kafka / Logstash 输出到 Elasticsearch
- git - 搞砸了推送到 github,现在想恢复更改
- php - wemos d1(作为客户端)和网络服务器(在 arduino 或 wemos d1 上)通过 LAN 进行通信
- javascript - 如何将 facebook 插件页面集成到博客中?
- regex - 如何在ansible中的两个点之间获取字符串
- python - 如何在 MAC OS 中将 python 2.7 与最新的 openssl 版本链接?
- google-sheets - 让它显示一个唯一的单元格范围,具体取决于哪个单元格为 TRUE
- python-3.x - pandas 高级逗号分割
- regex - Excel VBA - Regex.Escape 方法
- linux - 使用 noxsave 禁用 avx 指令