繁体   English   中英

jQuery内部函数不起作用

[英]jQuery inside function not working

setTimeout( myFunction, 1000 );
function myFunction() {
$('#content').delegate('#fileList', 'fileActionsReady',function(ev){
                var $fileList = ev.fileList.$fileList;
                $fileList.find('tr').each(function(){
                    $filename = $(this).attr('data-file');
                    $owner = $(this).attr('data-share-owner');  
                    $id = $(this).attr('data-id');
                    getState($id,$filename,$owner,"true");
  setTimeout( myFunction, 5000 );
}

如您所见,我正在尝试循环一个在页面中列出特定表的函数,然后它调用另一个函数来更新信息。 现在我在函数外部使用此代码没有任何问题,但是当我将其放在函数内部时,它将停止工作。 我是javascript的新手,因此经过数小时的搜索后我仍然没有发现问题所在。

正如我在评论中所说的那样(在另一个答案中执行复制/粘贴之前),实际上,每调用myFunction触发一次myFunction ,实际上每隔5秒就会添加一个事件侦听器,因为您这样做:

function myFunction() {
    // this below adds an event listener every time
    $('#content').delegate('#fileList', 'fileActionsReady',function(ev){

我的建议是修改myFunction并将其设置为fileActionReady回调函数(不确定是否触发一次或连续触发)。 因此,您的最终代码应如下所示:

$('#content').delegate('#fileList', 'fileActionsReady', myFunction);

function myFunction(ev) {
            var $fileList = ev.fileList.$fileList;
            $fileList.find('tr').each(function(){
                $filename = $(this).attr('data-file');
                $owner = $(this).attr('data-share-owner');  
                $id = $(this).attr('data-id');
                getState($id,$filename,$owner,"true");
            }
            setTimeout( function(){
                myFunction(ev)
            }, 5000 );
}

此代码的作用是从收到的第一个fileActionsReady事件开始,然后每5秒触发一次相同的函数。 如果您不想等待事件,可以手动触发该函数,只是不要忘记传递文件列表数据(如果确实需要)。


这是一个简单的例子来说明我的意思:

 $('#content').on('fileActionsReady', '#fileList', myFunction); function myFunction(ev) { $('#r').text('tick'); setTimeout(function() { $('#r').text(''); }, 2500) setTimeout(function() { myFunction(ev) }, 5000); } function fireEvent() { $('#fileList').trigger('fileActionsReady', [{ count: 1 }]); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button onclick="fireEvent()">Fire Event</button> <div id="r"></div> <div id="content"> <div id="fileList"></div> </div> 

function myFunction() {
        $('#fileList tr').each(function(){
            $filename = $(this).attr('data-file');
            $owner = $(this).attr('data-share-owner');  
            $id = $(this).attr('data-id');
            getState($id,$filename,$owner,"true");
        });
        setTimeout( myFunction, 5000 );
}
setTimeout( myFunction, 1000 );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM