首页 > 解决方案 > 突出显示 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>

标签: javascripthtmlcss

解决方案


  • ID 必须是唯一的
  • ps没有onsubmit事件
  • 你没有showResultgetFutureValue任何地方
  • 你没有任何东西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>


推荐阅读