我想知道是否有可能用JavaScript重寫現有的HTML元素屬性和屬性訪問器(getters和setters),以便當瀏覽器呈現html時,所有的賦值都歸屬於html代碼是用自定義功能預處理的。用Javascript覆蓋現有的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>
是類似的東西可能又如何呢? 我知道我可以在渲染並遍歷所有id後遍歷dom,但是我想知道是否可以攔截屬性和屬性的賦值,並在瀏覽器甚至呈現html之前在該級別執行此操作。
我提出的例子只是由一個來提出問題而且使得理解很簡單。
感謝
如果可能的話不要緊(它不是,你不能屬性的對象添加不存在),這是沒有意義的。 – adeneo
這是爲了樣式表或腳本版本嗎?如果是這樣,爲什麼不爲不同的CSS或腳本使用相同的ID,並動態加載所需的ID?或者你只是普遍好奇?我不知道用法是什麼,但我懷疑瀏覽器在創建DOM時會調用屬性訪問器。 –
我試圖解決另一個更大的項目問題,我對這個想法感到好奇,我認爲如果可能的話,當它建立javascript框架和庫時會有一些很好的用處。等等。 – darkgaro