jQuery function doesn't work when scrolling the page

时间:2016-10-20 13:04:17

标签: jquery

I use the function at the top of the page to show span on mouse click:

jQuery(document).ready(function($) {
    $('#contact').click(function() {
        $(this).find('span').text( $(this).data('last') );
    });
});

And this work untill I scroll the page into the footer. Than when I move up and click again, the function doesn't work. How to make this function work once per session or per page load?

1 个答案:

答案 0 :(得分:2)

When you scroll down and then up, verify if the #contact element still exists. If yes, check if the span inside still exists as well and the attr data-last.

You might have something that breaks your function to work.

Besides that your code looks good, but can be written better.

That $ sign inside function($) is weird...

If you manipulate #contact, try to add an event delegate with $(document).on([method], [element]), that will listen #contact even if it is manipulated.

//jQuery = $ sign
$(document).ready(function() {
    $(document).on('click','#contact', function() {
        $(this).find('span').text( $(this).data('last') );
    });
});

2nd solution - if you have some conflicts with jQuery library stay with jQuery instead of $

jQuery(document).ready(function($) {
    $(document).on('click','#contact', function() {
        $(this).find('span').text( $(this).data('last') );
    });
});