2014-03-06 113 views
1

我想知道是否有可能用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之前在該級別執行此操作。

我提出的例子只是由一個來提出問題而且使得理解很簡單。

感謝

+1

如果可能的話不要緊(它不是,你不能屬性的對象添加不存在),這是沒有意義的。 – adeneo

+0

這是爲了樣式表或腳本版本嗎?如果是這樣,爲什麼不爲不同的CSS或腳本使用相同的ID,並動態加載所需的ID?或者你只是普遍好奇?我不知道用法是什麼,但我懷疑瀏覽器在創建DOM時會調用屬性訪問器。 –

+0

我試圖解決另一個更大的項目問題,我對這個想法感到好奇,我認爲如果可能的話,當它建立javascript框架和庫時會有一些很好的用處。等等。 – darkgaro

回答

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> 
0

您可以使用HTML像第二個值data-*屬性;

<div id="name" data-second="pre_name"></div> 

然後你就可以使用,

var div = document.getElementById('name'); 
div.getAttribute("data-second"); 
+0

我不認爲這真的與被問到什麼有關。 –

+0

覆蓋是不可能的,我建議替代方法 –

+0

如果他想要將數據與元素相關聯,這是一個很好的解決方案。但我認爲他所追求的是在創建特定屬性時調用代碼的方式。屬性訪問器可以在加載DOM後執行此操作(也許),但是我懷疑他們會在DOM創建時觸發 –