[英]How to assign and work with DOM elements as variables
我希望能夠將html元素分配給變量,然后像使用實際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");
您可以將jQuery對象傳遞給函數。
var showAlert = function ($el, mes){
$el.show();
$el.append('<p>'+ mes +'</p>');
};
showAlert($('.item'), 'My Message');
您可以在下面執行類似的操作。 這將使用您傳遞的ID並向div顯示適當的消息。 您只需要確保在檢查元素之前等待DOM完全加載即可。
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
</head>
<body>
<div class="alert" id="custAlert" style="display: none"></div>
<input type="button" class="showError" value="click me to show error" />
<script type="text/javascript">
function showAlert(divID, msg) {
$('#' + divID).html(msg);
$('#' + divID).show();
}
$(function() {
$('.showError').click(function() {
showAlert('custAlert', 'this is an error');
});
});
</script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.