2016-06-29 2 views
0

Мне нужно передать значение 7 в качестве параметра, когда я вызываю функцию check_scroll().Значение переменной перехода Javascript от одной функции к другой

Но теперь значение lastcount продолжает расти, хотя я звоню check_scroll().

Пожалуйста, держите меня за предложение.

Проверьте фрагмент кода, как, как я говорю,

сначала нажмите на кнопку first click me to initiate check_scroll function, затем прокрутить внутри div, вы получите уведомление со значением приращением на 7.

Затем нажмите на кнопку, а затем снова прокручивать, но теперь предупреждение обыкновение начинаться с 7.

$("#mybutton").click(function() { 
 

 
    check_scroll(7); 
 

 
    }) 
 

 
    function check_scroll(val) { 
 

 
    var lastcount = val; 
 
    $('#notification_ul').scroll(function() { 
 
     if ($('#notification_ul').scrollTop() + $('#notification_ul').innerHeight() == $('#notification_ul')[0].scrollHeight) { 
 

 
      $("#notification_ul").append("<br/> Some Text Append <br/>"); 
 
      alert(lastcount); 
 

 
     lastcount = lastcount + 7; 
 
     } 
 

 
    }) 
 
    }
div { 
 
    width: 200px; 
 
    height: 200px; 
 
    overflow: auto; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="notification_ul"> 
 
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has 
 
    survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing 
 
    software like Aldus PageMaker including versions of Lorem Ipsum. 
 
</div> 
 

 
<button id="mybutton"> 
 
    first click me to initiate check_scroll function 
 
</button>

+4

Каждый раз, когда вы звоните 'check_scroll()', вы создания ** новый ** прокрутки обработчика - ранее установленные обработчики-прежнему будет вызвана. После того, как вы нажмете кнопку 5 раз, будет вызываться 5 обработчиков событий прокрутки. Каждый из них начнет с 'lastcount' в 7, но каждое событие прокрутки увеличит счетчик. – Pointy

+0

Извините, как это исправить. Мне нужно увеличивать с 7 каждый раз, когда я нажимаю кнопку. –

+0

Объявите глобальные функции 'lastcount = 7' глобально. dosn't передать его в check_scroll и продолжать увеличивать функцию, как вы делаете прямо сейчас. – Bsienn

ответ

1
  • определить scroll событие только один раз
  • движение lastcount к внешним
  • , когда кнопка нажата, сброс lastcount
$(function(){ 
    var lastcount = 0; 

    $("#mybutton").click(function() { 
     check_scroll(7); 
    }); 

    $('#notification_ul').scroll(function() { 
     if (lastcount !== 0) { 
      if ($('#notification_ul').scrollTop() + $('#notification_ul').innerHeight() == $('#notification_ul')[0].scrollHeight) { 
       $("#notification_ul").append("<br/> Some Text Append <br/>"); 
       console.log(lastcount); 
       lastcount = lastcount + 7; 
      } 
     } 
    }); 
}); 

function check_scroll(val) { 
    lastcount = val; 
} 
+0

Спасибо @iownthegame, ваше решение сработало, и ваше объяснение тоже хорошо. –

+0

И еще 1 сомнение, почему это происходит на самом деле? Можете ли вы объяснить немного больше? –

+0

На самом деле я не знаю, что произойдет, я также хочу, чтобы кто-то сказал мне, почему. Однако мои знания говорят мне привязывать каждое событие только один раз. см. http: // stackoverflow. com/questions/8408826/bind-event-only-once и http://stackoverflow.com/questions/2180326/jquery-event-model-and-preventing-duplicate-handlers – iownthegame

0

окончательный ответ после того, как со ссылкой ваши предложения, спасибо вам, ребята, за быстрое решение и предложение. Недурно

var lastcount = 7; 
 
$("#mybutton").click(function() { 
 
\t check_scroll(7); 
 
}) 
 

 
$('#notification_ul').scroll(function() 
 
{ 
 
    if ($('#notification_ul').scrollTop() + $('#notification_ul').innerHeight() == $('#notification_ul')[0].scrollHeight) 
 
    { 
 
\t \t 
 
    $("#notification_ul").append("<br/> Some Text Append <br/>"); 
 
    
 
    alert("last count after scroll " + lastcount); 
 
\t \t 
 
    lastcount = lastcount + 7; 
 
    } 
 

 
}) 
 

 
function check_scroll(val) { 
 
\t lastcount = val; 
 
\t alert("Last count reseted to " + lastcount); 
 
}
div { 
 
    width: 200px; 
 
    height: 200px; 
 
    overflow: auto; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="notification_ul"> 
 
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has 
 
    survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing 
 
    software like Aldus PageMaker including versions of Lorem Ipsum. 
 
</div> 
 

 
<button id="mybutton"> 
 
    sometext 
 
</button>

Смежные вопросы