Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

javascript - Jquery previous .html() element still showing when new element clicked

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...