span35斤黄瓜spanspan27斤西红柿spanspan元span功能要求1从页面中获取上面html页面span 标签使用样式选择器2正确获取元素内容 innerHTML3正确使用 parseint 获取整数值4正确是 parseFloat 获取浮点值5正确计算 2 斤黄瓜 3 斤西红柿的总价6将结果使用 innerHTML 放入页面的 span 总价标签中
1.使用样式选择器获取元素:
const cucumberPrice = document.querySelector('span:nth-of-type(1)'); const tomatoPrice = document.querySelector('span:nth-of-type(2)'); const totalPrice = document.querySelector('span:nth-of-type(3)');
2.获取元素内容:
const cucumberPriceValue = cucumberPrice.innerHTML; const tomatoPriceValue = tomatoPrice.innerHTML;
3.使用 parseInt 获取整数值:
const cucumberPriceInt = parseInt(cucumberPriceValue); const tomatoPriceInt = parseInt(tomatoPriceValue);
4.使用 parseFloat 获取浮点值:
const cucumberPriceFloat = parseFloat(cucumberPriceValue); const tomatoPriceFloat = parseFloat(tomatoPriceValue);
5.计算总价:
const totalWeight = 2 + 3; const totalCucumberPrice = totalWeight * cucumberPriceFloat; const totalTomatoPrice = totalWeight * tomatoPriceFloat; const totalPriceValue = totalCucumberPrice + totalTomatoPrice;
6.将结果放入页面的总价标签中:
totalPrice.innerHTML = totalPriceValue.toFixed(2); // 保留两位小数,toFixed 方法返回字符串类
原文地址: https://www.cveoy.top/t/topic/cHtg 著作权归作者所有。请勿转载和采集!