只有在准备好文档内的警报后才触发工作

时间:2016-03-29 22:41:32

标签: javascript jquery javascript-events

我有这段代码:

$(document).ready(function () {
            active_menu('mn_tours');
            $('#buscar').val(localStorage.getItem("busqueda"));
            $('#btbuscar').trigger('click');
        });

我希望在页面加载时立即触发该按钮上的提交事件,但它似乎不起作用,但是当我把它放在:

$(document).ready(function () {
            active_menu('mn_tours');
            $('#buscar').val(localStorage.getItem("busqueda"));
            alert('Something');
            $('#btbuscar').trigger('click');
        });

它确实有效,但我不知道如何解决这个问题。

2 个答案:

答案 0 :(得分:0)

通过初步测试,此代码有效......

(function() {
var app = angular.module('peopleController', []);

app.controller('PeopleController',
function($scope, $http) {
var url = 'http://localhost:3000/api/people';
$http.get(url)
.success(function(people) {
$scope.people = people;
})
.error(function(data) {
console.log('server side error occurred.'); 
}); 
} 
);
})(); 

没有看到你原来的按钮监听器分配,我无法判断这是否正是你想要的,但如果听众设置得当,这个方法就可以了。

答案 1 :(得分:-1)

你有调整问题。当javascript运行时:

$('#btbuscar').trigger('click');

HTML元素尚不存在,因此提交永远不会发生。

警报将暂停javascript执行。因此,当您单击“确定”时,页面上已加载HTML元素 #btbuscar 并且提交工作。

它不安全,但您可以使用setTimeout

$(document).ready(function () {
    active_menu('mn_tours'); 
    setTimeout(function(){
        $('#buscar').val(localStorage.getItem("busqueda"));
        $('#btbuscar').trigger('click');
    },1000);
});
相关问题