javascript - 清理 javascript dom 脚本?

标签 javascript html dom

嗨,有没有更好的方法或(更干净的方法)来创建 dom 元素?比如数组之类的?

示例代码:

$hubbe.toolbarLeft = document.createElement('DIV');
$hubbe.toolbarLeft.setAttribute('id', 'toolbar-left');
$hubbe.toolbarLeft.style.width = '50px';
$hubbe.toolbarLeft.style.height = '100%';
$hubbe.toolbarLeft.style.position = 'fixed';
$hubbe.toolbarLeft.style.left = '0';
$hubbe.toolbarLeft.style.backgroundColor = 'grey';
$hubbe.toolbarLeft.style.color = 'white';
$hubbe.toolbarLeft.style.textAlign = 'center';
document.body.appendChild($hubbe.toolbarLeft);`

最佳答案

有一些库和框架可以帮助您实现这一点,例如 jQuery。如果您坚持使用普通 JavaScript,则可以通过 Object.assign() 批量设置属性来简化一点:

Object.assign($hubbe.toolbarLeft.style, {
    width: '50px',
    height: '100%',
    position: 'fixed',
    left: '0',
    backgroundColor: 'grey',
    color: 'white',
    textAlign: 'center',
});

关于javascript - 清理 javascript dom 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50487036/

相关文章:

php - 防止 HTMLPurifier 和 DOMDocument 转换为 Â

javascript - 以编程方式更改类名

Selenium:selenium 如何识别元素可见与否?它有可能加载到 DOM 中但不呈现在 UI 上吗?

javascript - 为什么这个 JSON 文件读起来很奇怪

javascript - 如何动态检查 "checkbox"- jQuery Mobile

javascript - 在不移动页面 View 的情况下显示隐藏的div

javascript - Bootstrap 表单验证在没有控制台错误的情况下无法正常工作

javascript - 使用 Node-jsCoverage 、 Mocha 和 Express 进行功能测试覆盖率报告

javascript - 如果另一个使用 bootstrap 打开,则关闭 div

javascript - 在每个悬停事件上生成随机 Logo 颜色