2015-04-28 56 views
0

我需要爲我的應用程序創建通知計數器。目前,我想在每個按鈕點擊的圖片上添加越來越多的。這怎麼能用jQuery來實現?
JSfiddle
jQuery - 爲每次點擊添加越來越多的圖像

HTML:

<img id="header_bell_notificator" class="show_notif" src="http://www.gsi.co.ir/Docs/Images/Red_Circle.png" alt="" width="30px"> 
<button id="kick_button">click this</button> 

CSS:

.show_notif{ 
    visibility: hidden; 
} 

JS:

var counter=0; 
$("#kick_button").click(function() {$("#header_bell_notificator").removeClass("show_notif"); 
    }); 
+0

試試這個http://jsfiddle.net/vk5j72s3/你需要額外的格計數器 –

+0

謝謝,但我需要這個數字在圖像上。 – undroid

+2

http://jsfiddle.net/vk5j72s3/1/只是將櫃檯移動到正確的位置:) –

回答

1

有幾個MODS的你的實現......

  • 包裝DIV對包裝圖像
  • data-counter屬性
  • 使用:before僞元素顯示計數器

,你可以得到的東西是這樣的:

jsfiddle

var counter=0, 
 
    $bellNotificator = $('#header_bell_notificator'), 
 
    $bellNotificatorImg = $bellNotificator.find('img'); 
 

 
$("#kick_button").click(function() { 
 
    counter++; 
 
    $bellNotificator.attr('data-counter', counter); 
 
    $bellNotificatorImg.removeClass("show_notif"); 
 
});
body { 
 
    font-family: helvetica,arial,sans-serif; 
 
} 
 
#header_bell_notificator { 
 
    float:left; 
 
    width: 30px; 
 
    height: 30px; 
 
    margin: 5px; 
 
    position: relative; 
 
} 
 
#header_bell_notificator:before { 
 
    content: attr(data-counter); 
 
    position: absolute; 
 
    line-height: 30px; 
 
    width: 30px; 
 
    text-align: center; 
 
    color: #fff; 
 
    font-size: .8em; 
 
    font-weight: bold; 
 
} 
 

 
.show_notif{ 
 
    visibility: hidden; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="header_bell_notificator"> 
 
    <img class="show_notif" src="http://www.gsi.co.ir/Docs/Images/Red_Circle.png" alt="" width="30px" /> 
 
</div> 
 
    
 
<button id="kick_button">click this</button>

0

簡單地嘗試這樣的:

UPDATED FIDDLE

$("#kick_button").click(function() { 
     var counter = parseInt($('.counter').html()) + 1; 
     $('.counter').html(counter); 
    }); 

,添加一個名爲<div class="counter">0</div>

0

的一種方法是將圖像移動到的背景,然後改變其內部HTML容器。 像這樣:

var counter=0; 
$("#kick_button").click(function() { 
    counter++; 
    $("#header_bell_notificator").removeClass("show_notif").html(counter); 
}); 

這裏的updated fiddle