javascript 如何使用js函数在调用函数的位置插入文本?

cl25kdpy  于 2023-01-07  发布在  Java
关注(0)|答案(2)|浏览(176)

我想写一些类似下面的html和js代码,我可以在html的文本中多次调用Walking函数,并让该函数进行计算并将结果放置在script标记的位置。
但是我找不到一个合适的js函数来把html写在正确的地方,而不必定义一个给定id的span元素,我每次都必须通过这个id传递给函数。

function Walking(distance, ascent, descent) {
  // Calculate walking time from distance, ascent and descent 
  // and display this and other info at point the function is called.
}
Walk for
<script>
  Walking(1000, 100, 0);
</script> until you arrive at ... Then walk steeply uphill for
<script>
  Walking(2500, 1100, 0);
</script> to reach the summit.
2q5ifsrm

2q5ifsrm1#

这并不简单,但是您可以从下面的代码中学到很多东西。
组件:

const avgWalk = 4; // km/h
const ascWalk = 2;
const dscWalk = 4.5;
const decimalHoursToHHMM = num => { 
  let n = new Date(0,0); 
  n.setSeconds(+num * 60 * 60); // convert to seconds
  let [HH,MM] =  n.toTimeString().slice(0, 5).split(":"); // convert to HH:MM and spread the result to HH and MM
  return +HH === 0 ? `${+MM}m` : `${+HH}h${+MM}m`; // using template literals
};
// Calculate walking time from distance, ascent and descent 
// and display this and other info at point the function is called.

const Walking = ([distance, ascent, descent]) => decimalHoursToHHMM(
    (distance/1000)/avgWalk - 
    (ascent/1000)/ascWalk + 
    (descent/1000)/dscWalk);

window.addEventListener("DOMContentLoaded", () => { // when page has loaded
  document.querySelectorAll(".calc")  // all elements with class "calc"
   .forEach(span => span.textContent = Walking(JSON.parse(span.dataset.parms))); // use the data-parms for values and set the textContent
})
Walk for <span class="calc" data-parms="[1000, 100, 0]"></span> until you arrive at ... Then walk steeply uphill for
<span class="calc" data-parms="[2500, 1100, 0]"></span> to reach the summit.
Return trip should last <span class="calc" data-parms="[5000, 0, 5000]"></span>.
wqsoz72f

wqsoz72f2#

您可以使用document.currentScriptreplaceWith()来替换函数调用脚本元素(例如,使用文本):

<script>
function addText() {
  document.currentScript.replaceWith(" and added text");
}
</script>

Default text<script>addText();</script>.

请注意,函数需要在调用发生的位置之前定义。

相关问题