我想知道是否可以使用Javascript覆盖现有的HTML Element属性和属性访问器(getter和setter),这样当浏览器呈现html时,html代码中某些属性的所有赋值都会使用自定义功能进行预处理。 / p>
以下是一个例子:
<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之前在该级别执行。
我提出的示例仅仅是为了解决问题并使其易于理解。
由于
答案 0 :(得分:0)
您可以将html data-*属性用作第二个值,例如;
<div id="name" data-second="pre_name"></div>
然后你可以使用,
var div = document.getElementById('name');
div.getAttribute("data-second");
答案 1 :(得分:0)
不幸的是,这是不可能的,您只能在加载后修改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>