是否可以创建一个在js中创建特定Dom元素的模块?

时间:2019-03-02 15:00:24

标签: javascript

我有一个问题。是否可以用Javascript创建一个可实例化Dom元素的模块?例如,我有data=""" Index Uniprot P1 P2 ID1 ID2 1 O00141 2r5tA_1 3hdmA_9 2r5tA 3hdmA 2 O00141 2r5tA_2 3hdmA_1 2r5tA 3hdmA 3 O00141 2r5tA_7 3hdmA_7 2r5tA 3hdmA 4 O15021 2w7rB_2 2w7rA_2 2w7rB 2w7rA """ #create the sample dataframe df = pd.read_csv(pd.compat.StringIO(data), sep='\s+') #Uniprot have to be sorted df = df.sort_values(by= 'Uniprot') dico = {} for i, row in df.iterrows(): key1 = row.Uniprot + 'C1';key2 = row.Uniprot + 'C2' if key1 not in dico: dico[key1] = [row.Uniprot, row.ID1, row.P1] dico[key2] = [row.Uniprot, row.ID2, row.P2] else: dico[key1] = dico[key1] + [row.P1] dico[key2] = dico[key2] + [row.P2] maxlen = max ([len(l) for l in dico.values()]) for k in dico.keys(): d = len(dico[k]) dico[k] = dico[k] + [''] * (maxlen - len(dico[k])) df_result = pd.DataFrame.from_dict(dico).T.reset_index(drop=True) print(df_result) 类。

        0      1        2        3        4
0  O00141  2r5tA  2r5tA_1  2r5tA_2  2r5tA_7
1  O00141  3hdmA  3hdmA_9  3hdmA_1  3hdmA_7
2  O15021  2w7rB  2w7rB_2                  
3  O15021  2w7rA  2w7rA_2 

我为格式错误感到抱歉,但我不知道如何改善格式。 此模块导出整个类,然后,我要在一个文件中使用它,我们将其称为Canvas。在那里,我通过调用class Canvas { constructor(width, height, context){ this.width = width; this.height = height; this.context = context; this.setupCanvas(); } setupCanvas(){ console.log(this.width, this.height, this.context); let canvas = document.createElement('canvas'); canvas.width = this.width; canvas.height = this.height; let context = canvas.getContext(this.context); context.fillStyle = 'red'; return canvas; } } export default Canvas; 导入模块。所以其余的代码看起来像

index.js

现在它不起作用,因为出现错误:TypeError:Node.appendChild的参数1('node')必须是Node的实例

1 个答案:

答案 0 :(得分:3)

您的代码有2个问题。首先,您的Canvas类不是画布节点,但是具有功能setupCanvas创建画布。接下来,您打算两次调用setupCanvas:一次是从构造函数调用,然后是canvas.setupCanvas;。但是请注意,canvas.setupCanvas;什么都没做,因为您缺少()

您可以做的是首先从构造函数中删除this.setupCanvas(),然后在以后调用时使用setupCanvas的结果:

import Canvas from './Canvas/canvas';

let canvas = new Canvas(80, 80, '2d');
document.body.appendChild(canvas.setupCanvas());