如果设置了带有ID的cookie,我试图找到如何将类添加到div的方法。使用https://github.com/js-cookie/js-cookie。当我们点击带有“bar-info”类的Button时设置Cookie。但是我不知道如何读取cookie(Cookies.get),当文档准备就绪时,将class(hidden)添加到div,其ID与我们设置为cookie的ID相同。有人能帮助我吗?
$('[different-id-bar]').each(function () {
var $bar = $(this);
var button = $bar.find('[data-dismiss="bar-info"]');
//var getCookieIdName = $(document).data('cookie-id');
var getCookieId = $(this).attr('data-cookie-id');
var cookieName = 'data-cookie-bar-' + $(this).attr('data-cookie-id');
//var $cookie = Cookies.get(cookieName, getCookieId);
//if ($cookie) {
//$bar.addClass('hidden');
//}
button.on('click', function () {
Cookies.set(cookieName, getCookieId, {expires: 300});
$bar.addClass('hidden');
});
//$(document).ready(function(){
//if (Cookies.get(cookieName, getCookieId)) {
//$bar.addClass('hidden');
//}
//});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js-cookie-plugin-local-destination"></script>
<div class="row row-main" data-cookie-id="2585646" different-id-bar>
<div class="message-info">
<p class="content">
<a href="#">Lorem ipsum dolor sit amet.</a>
</p>
<a href="#" class="btn-close" data-dismiss="bar-info"><span>Close</span></a>
</div>
</div>
答案 0 :(得分:0)
您可以使用DOM关系来获取所需的数据。此处.closest()
可用于遍历different-id-bar
元素。
//iterate each element and read cookie
$('[data-dismiss="bar-info"]').each(function(){
//Travese up to parent element
var $bar = $(this).closest('[different-id-bar]');
//Get the cookie id
var getCookieId = $bar.attr('data-cookie-id');
//Create cookie name
var cookieName = 'data-cookie-bar-' + getCookieId;
//Read cookie
var cookie = Cookies.get(cookieName);
//if cookie is defined and has value add css class
if(cookie !== undefined && cookie === getCookieId){
$bar.addClass('hidden');
}
});
//Bind the click handler
$('[data-dismiss="bar-info"]').on('click', function(){
//Travese up to parent element
var $bar = $(this).closest('[different-id-bar]');
//Get the cookie id
var getCookieId = $bar.attr('data-cookie-id');
//Create cookie name
var cookieName = 'data-cookie-bar-' + getCookieId;
$bar.addClass('hidden');
Cookies.set(cookieName, getCookieId, {expires: 300});
});