2016-08-19 2 views
0

자바 스크립트에서 함수를 선언했으며 일부 JQuery 코드에서이 함수를 click 이벤트 내에서 호출하고 호출하지 않습니다. 그리고 function 키워드를 사용하여 함수를 정의 할 때 함수를 기대한다고 말하면 함수를 표현식으로 사용해야합니다. 문서가 준비 될 때 전역 적으로 호출되는 것처럼 click 이벤트 외부에서 함수가 호출됩니다.자바 스크립트에서 선언 된 functoin을 호출 할 수 없습니다.

자바 스크립트는

당신은 재 선언하려고
var item_width = $('.item-slider').width(); 
var item_margin = (item_width-600)/5; //sum of 4 elements divided by 5 margin spaces 
var items = $('ul.item-slider>li'); 
var x = 0; 
$.each(items,function(index){ 
    $(this).data("id",x); 
    x = x+1; 
}); 

var x = function(){ 
    $.each(items,function(index){ 
     var pos = $(this).data('id'); 

     if($(this).data('id') < 1){ 
      var left =(pos-1) * 150 + (pos-1) * 10; 
      -Math.abs(left); 
      $(this).css("left",left); 
     } 
     else if($(this).data('id') === 1){ 
      $(this).css("left", 0); 
      console.log("positon is set to" + $(this).css("left")); 
     }   
     else if($(this).data('id') > 1){ 
      var left = (pos-1) * 150 + (pos-1) * 10; 
      $(this).css("left", left); 
      console.log("positon is set to " + $(this).css("left")); 
     } 
    }); 
} 

// commented x(); 

$(".explore_matches > button[name = 'pre']").click(function(){ 
    $.each(items,function(index){ 
     console.log("each working"); 
     $(this).data('id',"abc"); 
    }) 
    x(); 
    console.log("skipped"); 
}); 
+0

'여러 번 x'. 'var x = 0;','var x = function() {}'. 그건 틀렸어요. 한 번만 해독 할 수 있습니다. – eisbehr

+0

다른 변수 이름으로 변경하더라도 여전히 작동하지 않습니다. [mcve]에서 –

+0

jQuery 및 HTML하시기 바랍니다. – zer00ne

답변

1
var item_width = $('.item-slider').width(); 
var item_margin = (item_width-600)/5; //sum of 4 elements divided by 5 margin spaces 
var items = $('ul.item-slider>li'); 
var x = 0; 
$.each(items,function(index){ 
    $(this).data("id",x); 
    x = x+1; 
}); 

function needToCall(){ 
    $.each(items,function(index){ 
     var pos = $(this).data('id'); 

     if($(this).data('id') < 1){ 
      var left =(pos-1) * 150 + (pos-1) * 10; 
      -Math.abs(left); 
      $(this).css("left",left); 
     } 
     else if($(this).data('id') === 1){ 
      $(this).css("left", 0); 
      console.log("positon is set to" + $(this).css("left")); 
     }   
     else if($(this).data('id') > 1){ 
      var left = (pos-1) * 150 + (pos-1) * 10; 
      $(this).css("left", left); 
      console.log("positon is set to " + $(this).css("left")); 
     } 
    }); 
} 



$(".explore_matches > button[name = 'pre']").click(function(){ 
    $.each(items,function(index){ 
     console.log("each working"); 
     $(this).data('id',"abc"); 
    }) 
    needToCall(); 
    console.log("skipped"); 
}); 
관련 문제