我正在開發一個簡單的網絡應用程序,我需要在某些事件或條件後更新顯示的數據。這些數據分散在許多不同的地方,並在完全獨立的標記結構中。 我曾經使用過類,但是在使用類來編輯數據時發現了一些危險的情況(特別是當我們使用OOCSS時,並且有很多類我們想要改變,並且不應該被綁定到js數據或行爲)。下面的解決方案在這方面應該是無懈可擊的,但是因爲我以前從來沒有見過它被使用過,所以我擔心我可能會錯過一些東西。 像下面這樣的解決方案有什麼缺點嗎?使用數據屬性來編輯javascript內容有什麼缺點嗎?
實施例下面的代碼 - 使用jQuery
後續可被綁定到特定的數據改變事件:
$('.data[data-type=user_data]').each(function(){
$(this).find('.data[data-type=user_name]').html($.user.userName)
.end().find('.data[data-type=user_location]').html($.user.userLocation)
.end().find('.data[data-type=incident_date]').html($.user.incidentDate)
.end().find('.data[data-type=incident_cost]').html($.user.incidentCost)
.end().find('.data[data-type=user_hair_color]').html($.user.hairColor);
//more data will be added here ...
});
標記將是在一些地方:
<div class="data incident_result bubbled_box" data-type="user_data">
<h3>Some heading</h3>
<ul>
<li>Username: <span class="data highlight name" data-type="user_name">Igor Wassel</span></li>
<li>User location: <span class="data" data-type="user_location">Estonia</span></li>
<li>Provider: <span class="data" data-type="incident_date">21/08/11</span></li>
</ul>
其它地方的標記將包括其他數據,但一個完全不同的HTML結構內。