2016-06-02 2 views
2

두 경우에 함수를 실행해야합니다. 페이지가로드 될 때마다 하나씩, 요소가 클릭 될 때마다 하나씩 함수를 실행해야합니다. click 이벤트는 작동하지만 onload 이벤트는 작동하지 않습니다.여러 이벤트에서 함수 실행

$(document).ready(function(e) { 

var captcha; 

    $('#captcha').on('ready click',function(){ 
     function alphanumeric_unique() { 
      return Math.random().toString(36).split('').filter(function(value, index, self) { 
       return self.indexOf(value) === index; 
      }).join('').substr(2,8); 
     } 

     captcha = alphanumeric_unique(); 

     $(this).val(captcha); 
    }); 
}); 


<input type="text" readonly value="" id="captcha"> 

어떤 도움을 주시겠습니까?

+0

함수로합니다. 그런 다음 load에 함수를 호출하고이를 이벤트 핸들러에 할당합니다. –

답변

1

당신은 페이지로드에 클릭 이벤트를 트리거해야합니다

$(document).ready(function(e) { 

    $('#captcha').on('click',function(){ 
     function alphanumeric_unique() { 
      return Math.random().toString(36).split('').filter(function(value, index, self) { 
       return self.indexOf(value) === index; 
      }).join('').substr(2,8); 
     } 

     captcha = alphanumeric_unique(); 

     $(this).val(captcha); 
    }); 

    $('#captcha').trigger("click"); // it will automatically call click event 


}); 
+0

네, 내 경우에는 작동합니다. 고마워요.하지만 여전히, 제 지식으로는 두 번의 이벤트, 특히 클릭과로드를 사용할 수 있습니까? 나는 무엇이든 시도했기 때문에 나올 수 있었고 그것을 해결할 수 없었습니다. –

+0

내 knowlegde 당 .. 당신도로드 이벤트를 클릭 이벤트와 바인딩 할 수 없습니다 .. 당신은 클릭 이벤트를 호출하는 트리거 이벤트를 사용해야합니다 –

1

당신은 클릭 이벤트 이외의 기능을 넣어해야합니다. 그런 다음 페이지로드시 호출 할 수 있습니다.

$(document).ready(function(e) { 
    var captcha = alphanumeric_unique(); 
    $('#captcha').on('ready click', function() { 
    captcha = alphanumeric_unique(); 
    $(this).val(captcha); 
    }); 
}); 

function alphanumeric_unique() { 
    return Math.random().toString(36).split('').filter(function(value, index, self) { 
    return self.indexOf(value) === index; 
    }).join('').substr(2, 8); 
} 

이 함수를 click 이벤트 내에 넣으면 범위가 해당 이벤트 처리기로만 제한됩니다.

1

그냥 당신과 같이 기능을 다시 사용할 수 있습니다 별도로 기능을 설정하면

$(document).ready(function(){ 
    function alphanumeric_unique() { 
     return Math.random().toString(36).split('').filter(function(value, index, self) { 
      return self.indexOf(value) === index; 
     }).join('').substr(2,8); 
    } 
    var captcha = alphanumeric_unique(); 
    $('#captcha').on('click',function(){ 
     $(this).val(captcha = alphanumeric_unique()); 
    }); 
}); 
0

을 원하는 경우에 사용 :

function alphanumeric_unique() { 
    return Math.random().toString(36).split('').filter(function(value, index, self) { 
    return self.indexOf(value) === index; 
    }).join('').substr(2,8); 
} 

function update_captcha() { 
    $('#captcha').val(alphanumeric_unique()); 
} 

$(document).ready(function() { 
    // Update when document is ready 
    update_captcha(); 
    // Update when captcha is clicked 
    $('#captcha').click(update_captcha); 
}); 
관련 문제