湖南建设部网站,wamp搭建多个网站,手机网站模板尺寸,永川做网站的ESP32-Web-Server编程- JS 基础 4
概述
HTML 内联事件处理器#xff0c;你永远不应该使用 HTML 事件处理器属性——因为那些已经过时了#xff0c;使用它们是不好的做法。
在前端编程中#xff0c;除了将期望发生的事件写为 JS 文件外#xff0c;还可以使用一些组件自带…ESP32-Web-Server编程- JS 基础 4
概述
HTML 内联事件处理器你永远不应该使用 HTML 事件处理器属性——因为那些已经过时了使用它们是不好的做法。
在前端编程中除了将期望发生的事件写为 JS 文件外还可以使用一些组件自带的事件处理器。
比如可以使用 button 组件的 onclick 内联属性实现在网页上点击按钮切换 LED 灯图标的转变。
但是 HTML 和你的 JavaScript 内联属性混在一起不是一个好主意因为它使得整个文件变得难以阅读。
pbutton onclickdocument.getElementById(text).style.colorredRed Text/button
/p建议使用独立的函数来控制元素属性这样容易增加函数的可复用性并保持 HTML 和 JS 相对独立 pbutton onclickbgChange()Change Background/button/pscriptfunction bgChange() {const randomHex () #${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, 0)};document.body.style.backgroundColor randomHex();}/script需求及功能解析
本节主要演示 JavaScript 内联属性的用法以及通过建立独立的函数来完成同样的功能。读者可以对比两种处理方法。
示例解析
前端设计
前端代码建立了五个 button点击不同的 button 可以实现对应的文本颜色的切换。前四个 button 使用 onclick 内联属性。最后一个 button通过函数 bgChange() 来完成相同的功能。
bodyh1Change text style/h1p idtextThis text will change style./ppbutton onclickdocument.getElementById(text).style.colorredRed Text/button/ppbutton onclickdocument.getElementById(text).style.colorblueBlue Text/button/ppbutton onclickdocument.getElementById(text).style.displaynoneHide Text/button/ppbutton onclickdocument.getElementById(text).style.displayblockShow Text/button/ppbutton onclickbgChange()Change Background/button/pscriptfunction bgChange() {const randomHex () #${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, 0)};document.body.style.backgroundColor randomHex();}/scriptpimg idimageLamp srclight_on.png
/p
pbutton onclickdocument.getElementById(imageLamp).srclight_on.pngTurn on the light/button
/p
pbutton onclickdocument.getElementById(imageLamp).srclight_off.pngTurn off the light/button
/p示例效果
点击不同的按钮可以切换网页的显示效果 总结
1本节主要是演示在前端设计中通过 HTML 内联事件处理器或者 JavaScript 函数实现对应事件的处理。
2在前端开发中应尽可能使用 JavaScript 函数而不是 内联事件处理器后者在大型项目中维护不方便容易因为维护问题。
资源链接
1ESP32-Web-Server ESP-IDF系列博客介绍 2对应示例的 code 链接 点击直达代码仓库
3下一篇ESP32-Web-Server编程- JS 基础5
(码字不易感谢点赞或收藏)