2015-04-23 64 views
1

我有一个JavaScript函数,例如函数:运行时元素显示

function SuperTD(id,str,tooltip) { 
    return '<td id="' +id+ '" title="' +tooltip+ '">' +str+ '</td>'; 
} 

SuperTD打来电话,与许多元素连接在一起,而我不想改变它是如何工作(进不产生元素使用html字符串)。

,我需要触发时元素呈现的功能,例如:

function SuperTD(id,str,tooltip) { 
    var onwhat = 'onwhat="executeFixedFunction(' + "'" +id+ "'" + ')"'; 
    return '<td><div id="' +id+ '" title="' +tooltip+ '" ' +onwhat+ '>' +str+ '</div></td>'; 
} 

其中executeFixedFunction是:

function executeFixedFunction(id) { 
    $('#' + id).uploadFile({ 
    url:"/file/upload" 
    }); 
} 

怎样才是正确的情况下做到这一点?我需要初始化一个file-upload元素无处不在SuperTD

用户仍在使用Firefox 3.5。

编辑多个方面:

GridBuilder.render = function() { 
    // return from cache 
    var html = ''; 
    // calls html += SuperTD(...) 
    return html; 
} 

GridBuilder.renderTo = function(id) { 
    $('#'+id).html(this.render()); 
    // I guess this is where I should initialize the file upload, but still, is there another way? 
} 
+2

您可以使用['MutationObserver'](https://developer.mozilla.org/en/docs/Web/API/MutationObserver),但它非常复杂。我建议你改变你的函数SuperTD来启动文件上传(这更有意义),而不是使用观察者。 – DontVoteMeDown

+1

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events –

+1

或者,您可以将回调参数添加到函数定义中。 '函数(id,str,tooltip,callback){callback();}' –

回答

3

如果您已经使用jQuery,我会考虑做这种方式:

function superTD (id, str, tooltip) { 
    return $('<td/>', { 
    id: id, 
    title: tooltip, 
    text: str 
    }).uploadFile({ 
    url: '/your-url' 
    }) 

} 

然后你就可以拨打superTDappendTo方法将其插入到表行

2

您可以使用setTimeout函数延迟回调函数。

function SuperTD(id,str,tooltip) { 
    var onwhat = 'onwhat="executeFixedFunction(' + "'" +id+ "'" + ')"'; 
    setTimeout(function(){ executeFixedFunction(id) }, 1000); 
    return '<td><div id="' +id+ '" title="' +tooltip+ '" ' +onwhat+ '>' +str+ '</div></td>'; 
} 
+1

这不可靠。 –

1

一切都与放在一起略微修改Jakubs的建议。请参阅Plunkr

function superTD(id, str, tooltip, callback) { 
    var td = $('<td/>', { 
     id: id, 
     title: tooltip, 
     text: str 
    }); 

    var up = $('<span/>'); // <-- this elm will be replaced 
    td.append(up); 
    $('#container').append(td); 

    callback(up, str); 
} 

function onCreated(elm, fname) { 
    elm.uploadFile({ 
     url: '/url', 
     fname: fname 
    }); 
} 

$(document).ready(function() { 
    superTD(1, 'foo', 'bar', onCreated); 
    superTD(2, 'bar', 'foo', onCreated); 
});