我希望能夠將html元素分配給變量,然後像使用實際DOM元素一樣處理它。如何分配和使用DOM元素作爲變量
在這個例子中,當showAlert()函數被調用時,它需要傳入的ID,顯示div,因爲它的默認值是隱藏的,並在DIV中設置了一個文本值。
這樣做的最好方法是什麼?
HTML:
<div class="alert" id="myCustomAlert12345" style="display:none" >
</div>
的Javascript:
function showAlert(alertDivID, alertMessage, alerttype){
if(alertDivID&& alertMessage){
currentDiv = $('#'+alertDivID);
currentDiv.show();
currentDiv.html(alertMessage);
}
}
showAlert("myCustomAlert12345","some error message goes here","error");
這段代碼對我來說似乎很好。不知道這裏的問題是什麼。 – 2012-02-17 22:13:27
是否是「offpage DOM」的同義詞?這裏有些相關:http://stackoverflow.com/q/9319017/575527 – Joseph 2012-02-17 22:15:44
除非你想使用全局變量,否則確保在'currentDiv'的第一個實例之前使用'var'語句,以便在本地創建變量。 – Jasper 2012-02-17 22:19:07