2015-04-23 106 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); 
});