我想知道是否可以使用 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/