Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have to write code which finds all anchors and attaches a function that displays a popup of the elements text. My code is probably a mess, but I was able to get it working however the issue I have now is:

If I click link 1, then link 2, then click link 1 again, it displays link 2's text however if i click it again it displays the correct text.

I am not sure exactly how to rewrite or go about fixing this code to properly display the element which is clicked, text all the time.

here is a jsfiddle example: http://jsfiddle.net/2aLfL/1/

$(document).ready(function() {

function deselect(e) {
  $('.pop').slideFadeToggle(function() {
    e.removeClass('selected');
});    
}

$(function() {
   $('a').click(function(){
     if($(this).hasClass('selected')){
     deselect($(this));

} else {
  $(this).addClass('selected');
  $('.pop').slideFadeToggle();
    var elText = $(this).text();
    $('#elPop').html("<p>" + "<br><br>" + "You just clicked: <br><b>" + elText + "</b><br><br><br>" + "Click anywhere to Close" + "</p>");
    console.log(this);

    $("#closeWin").click(function () {
        $('.anchorpop').hide();
    });
}
return false;
});
});

    $(function close(){
 $(document).click(function(){  
  $('.anchorpop').hide();
  });
});


$.fn.slideFadeToggle = function(easing, callback) {
  return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);
};
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
183 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're binding the following click handler

    $("#closeWin").click(function () {
      $('.anchorpop').hide();
    });

inside <a> click handler so whenever a link is clicked, multiple handlers are being added.

You can avoid many unnecessary code using toggleClass() method.

You can also bind same event handlers to multiple elements by passing additional selectors.

after all your code boils down to

$(function () {
  $('a').click(function () {
    var htmlString = "<p>" + "<br><br>" + "You just clicked: <br><b>" + $(this).text() + "</b><br><br><br>" + "Click anywhere to Close" + "</p>"
    $('.pop').html(htmlString).slideFadeToggle(function () {
        $(this).toggleClass('selected');
    });
  return false;
  });
  $("#closeWin, .anchorpop").click(function () {
    $('.anchorpop').hide();
  });
});

and the custome slideFadeToggle function.

Updated Fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...