javascript - 使用 Javascript 覆盖现有 HTML 元素属性和属性

标签 javascript html dom

我想知道是否可以使用 Javascript 覆盖现有的 HTML 元素属性和属性访问器(getter 和 setter),以便当浏览器呈现 html 时,对 html 代码中某些属性的所有分配都可以使用自定义功能进行预处理。

这是一个例子:

<html>
<head>
<script>

// JS code would go here which would override default behavior 
// for example if I wanted to reformat id="name"  so its actually
// registered as id="pre_name" once browser renders the html  


</script>

</head>
<body>

<!-- here we are assigning the 'name' to id , but behind the scene we really want it to be 'pre_name' -->
<div id="name"></div>

<script>
    // when we try to access the id it would actually match the overwritten one 
    console.log(document.body.children[0].id)  // would output pre_name
</script>

</body>
</html>

这样的事情可能吗?如何实现? 我知道我可以在渲染后遍历 dom 并更改所有 id,但我想知道是否可以拦截属性和属性的分配,并在浏览器渲染 html 之前在该级别执行此操作。

我提供的示例只是为了呈现问题而编造的,而且很容易理解。

谢谢

最佳答案

不幸的是,这是不可能的,您只能在加载后修改 name 元素。 所以它会是这样的:

<body>

<!-- here we are assigning the 'name' to id , but behind the scene we really want it to be 'pre_name' -->
<div id="name"></div>
<script>
    // right after
    document.getElementById('name').id = 'pre_name';
</script>

<script>
    // when we try to access the id it would actually match the overwritten one
    console.log(document.body.children[0].id)  // would output pre_name
</script>

</body>

甚至

<body>

<!-- here we are assigning the 'name' to id , but behind the scene we really want it to be 'pre_name' -->
<div id="name"></div>

<script>
    // or here
    document.getElementById('name').id = 'pre_name';
    // when we try to access the id it would actually match the overwritten one
    console.log(document.body.children[0].id)  // would output pre_name
</script>

</body>

关于javascript - 使用 Javascript 覆盖现有 HTML 元素属性和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22231921/

相关文章:

javascript - 需要一种更优雅的方式来使用 jQuery 在 dom 树中查找元素

javascript - 链+过滤器+值返回值不就是一个函数吗?

javascript - HERE折线编码: JavaScript -> Swift

html - vbscript在html表中显示数据库查询

javascript - 查找绝对定位元素的引用系

javascript - 在离线页面中使用 javascript

由于...CSS,PHP 邮件表单文本框无法编辑?

html - 删除显然不需要的垂直滚动条

dom - ExtJS4:查找树节点的 DOM 元素

javascript - 无法访问span标签的innerHTML