Я пробовал все три, и каждый из них работает только один раз, и я должен обновиться, чтобы заставить его работать снова. Вот мой код.
$(document).ready(function(){
$('#notificationTB').on('click', function(){
document.getElementById('notificationTB').src='img/notifC.png';
$('#notifBox').css('display', 'block');
$(this).on('click', function(){
document.getElementById('notificationTB').src='img/notif.png';
$('#notifBox').css('display', 'none');
});
});
});
благодаря
Похоже, вы пытаетесь переключаться между двумя состояниями. Как вы это делаете, это не очень хорошо, так как обычно это плохая форма для определения элемента click-обработчика элемента в его собственном обработчике кликов, тем более, что в этом случае старый не удаляется. Попробуй это:
$(document).ready(function(){
$('#notificationTB').on('click', function(){
var self = $(this); //refers to this element - $('#notificationTB')
if(self.attr("src") == "img/notif.png"){
self.attr("src", "img/notifC.png");
$('#notifBox').css('display', 'block'); //.show() or .hide() will also do this
} else {
self.attr("src", "img/notif.png");
$('#notifBox').css('display', 'none');
}
});
});
Просто используйте .toggle()
для переключения между display: block
и display: none
:
$(document).ready(function(){
$('#notificationTB').on('click', function(){
$('#notificationTB').attr('src',function(i,str) {
return (str=='img/notifC.png') ? 'img/notif.png' : 'img/notifC.png';
});
$('#notifBox').toggle();
});
});
или еще лучше:
$(document).on('click', '#notificationTB', function(){
$(this).attr('src',function(i,str) {
return (str=='img/notifC.png') ? 'img/notif.png' : 'img/notifC.png';
});
$('#notifBox').toggle();
});
});
http://api.jquery.com/attr/#attr-attributeName-functionindex--attr
Попробуй это
$(document).ready(function(){
$(document).on('click', '#notificationTB', function(){
document.getElementById('notificationTB').src='img/notifC.png';
$('#notifBox').css('display', 'block');
$(this).on('click', function(){
document.getElementById('notificationTB').src='img/notif.png';
$('#notifBox').css('display', 'none');
});
});
});
альтернативно, вы, скорее всего,
$(document).on('click', '#notificationTB', function(){
$('#notificationTB').attr('src','img/notifC.png');
$('#notifBox').css('display', 'block');
$(this).on('click', function(){
$('#notificationTB').attr('src','img/notif.png');
$('#notifBox').css('display', 'none');
});
});
Почему вы используете getElementById, когда у вас есть jQuery?
$(document).ready(function(){
$('#notificationTB').on('click', function(){
var $box = $('#notifBox'), $this = $(this);
$box.toggle();
if($box.is(":visible")){
$this.attr('src','img/notifC.png');
}else{
$this.attr('src','img/notif.png');
}
});
});