我正在嘗試在此答案中使用 css 和 div 創建通知。
但是我需要不止一個通知,所以我序列化了 div 的 id。
問題是,當我宣告 click 函式時,變數nname不會被評估 - 只有當我點擊關閉按鈕時才會被評估。所以只有最后一個通知被駁回。
如何使用變數“nname”的值宣告函式?
我發現了一個類似的帖子,但它是關于 zsh 的。
nc = 0;
function show_notification(data){
nname = "notification_" nc
$('body').append('<div id="' nname '" style="display: none;"><span ><a title="dismiss notification">x</a></span></div>');
$('#' nname).fadeIn("slow").append('some new information');
$('#' nname ' .dismiss').click(function(){$("#" nname).fadeOut("slow");});
nc ;
}
uj5u.com熱心網友回復:
問題是,該變數nname不是唯一的每次呼叫時間show_notification-通過不添加let/ var/const它成為一個全域變數,所以當你點擊第1 [X]變數已更改為指向最近的。
雖然有一些方法可以解決這個問題,但您可以通過使用.appendTo為您提供一個包含新內容的變數然后在該變數上使用 jquery 方法來消除對增量 ID 的需要。
var newDiv = $("your html").appendTo("body");
newDiv.fadeIn();
在單擊處理程式中,使用thisDOM 導航關閉選定的彈出視窗。
....click(function() {
$(this).closest(".notification").fadeOut();
});
function show_notification(data) {
var newDiv = $('<div style="display: none;"><span ><a title="dismiss notification">x</a></span></div>')
.appendTo("body");
newDiv.fadeIn("slow").append('some new information:' data);
newDiv.find(".dismiss").click(function() {
$(this).closest(".notification").fadeOut("slow");
});
}
// Add some notifications
show_notification("1");
setTimeout(() => show_notification("two"), 500);
.dismiss { color: red; margin-right: 0.5em; border: 1px solid #FCC; cursor: pointer }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
uj5u.com熱心網友回復:
這是您問題的解決方案。我已經在你的錨標簽中給出了你的通知 ID 的數量,并提取了相同的數量來洗掉特定的通知。
nc = 0;
function show_notification(){
nname = "notification_" nc
$('body').append('<div id="' nname '" style="display: none;"> <span><a title="dismiss notification" data-id = "' nc '" >Close</a></span> </div>');
$('#' nname).fadeIn("slow").append('some new information');
nc ;
}
$(document).on("click",".dismiss",function() {
var findid = $(this).attr('data-id');
$("#notification_" findid).fadeOut("slow");
});
show_notification();
show_notification();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/375459.html
