Javascript 在多个事件上运行函数
我需要在两种情况下运行一个函数。一种是加载页面时,另一种是每次单击元素时。单击事件有效,但onload事件无效Javascript 在多个事件上运行函数,javascript,jquery,click,onload,Javascript,Jquery,Click,Onload,我需要在两种情况下运行一个函数。一种是加载页面时,另一种是每次单击元素时。单击事件有效,但onload事件无效 $(document).ready(function(e) { var captcha; $('#captcha').on('ready click',function(){ function alphanumeric_unique() { return Math.random().toString(36).split('').fil
$(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">
$(文档).ready(函数(e){
var验证码;
$('#captcha')。在('ready click',function()上{
函数字母数字_unique(){
返回Math.random().toString(36).split(“”).filter(函数(值,索引,self){
返回self.indexOf(value)==索引;
}).连接('')。子节(2,8);
}
captcha=字母数字_唯一();
$(this.val)(验证码);
});
});
有什么帮助吗?您需要在页面加载时触发单击事件:
$(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
});
您需要将函数置于click事件之外。然后可以在页面加载时调用它
$(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事件中,则作用域将仅限于该事件处理程序。只需单独设置函数,并在您喜欢的任何事件上使用它即可
$(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());
});
});
您可以重复使用以下功能:
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);
});
是的,这在我的情况下是有效的,谢谢。但是,就我所知,我可以使用两个事件,特别是点击和上传吗?因为我尝试了我能想到的任何方法,但没有解决它。根据我的知识..不,你也可以将加载事件与单击事件绑定..你必须使用触发器事件调用任何单击事件使其成为一个函数。然后在加载时调用函数,并将其分配给事件处理程序。