将 HTML 对象添加到事件 javascript/meteor

Add HTML object to an event javascript/meteor

如何将 HTML 个对象添加到事件中?
我想做这样的事情:

Template.Schedule.events({
    'dblclick .mycol' (event){
        event.target.childNodes.append("<strong>Test</strong>");
    }
});

我知道我可以为给定的示例设置样式并更改内部 HTML 等等,但实际上我想添加其他 HTML 对象,例如 select-标签,我该怎么做?

普通 JS 方式

您可以在此处使用 innerHTML 来更改单击元素的 html 内容:

'dblclick .mycol' (event){
  const target = event.currentTarget
  target.innerHTML = target.innerHTML + "<strong>Test</strong>"
}

如果你想在事件中操纵父级你可以使用outerHTML

jQuery方式

您使用 append 的方法需要 jQuery:

'dblclick .mycol' (event){
  $(event.currentTarget).append($("<strong>Test</strong>"))
}

奖励:使用 jQuery

的优化

在 meteor blaze 模板事件中,每个事件都有一个对模板实例的引用。此模板实例保留 a reference to a jQuery object 并且它是它操作的 DOM 的一部分。

template.$ returns a jQuery object of those same elements. jQuery objects are similar to arrays, with additional methods defined by the jQuery library.

The template instance serves as the document root for the selector. Only elements inside the template and its sub-templates can match parts of the selector.

如果您的秒事件参数是 namend templateInstance,您可以通过 templateInstance.$ 访问它。有

'dblclick .mycol' (event, templateInstance){
  templateInstance.$(event.currentTarget).append($("<strong>Test</strong>"))
}

这节省了 jQuery 遍历整个 DOM 的需要,使其在大型文档上更有效率。

流星烈焰之道

现在,当需要进行小规模操作时,这些都是巧妙的小技巧。但是,您可能希望您的应用程序具有可扩展性并始终从 Blaze 渲染引擎中获利。

在这种情况下,您可能更希望生成一种动态插入模板的方法。

考虑以下尚未导入的模板:

rowcontent.html

<template name="rowcontent">
    <strong>Test</strong>
    <p>someData{{someData}}</p>
</template>

rowcontent.js

import './rowcontent.html' // currently just the import

您可以在运行时使用 Blaze.renderWithData 将其动态添加到元素中,因此:

'dblclick .mycol' (event, templateInstance) {
    import './rowcontent.js' // use the right path here
    Blaze.renderWithData(Template.rowcontent, {someData: 'toBePassedToRowContent'}, event.currentTarget)
 }

这将导致:


这是我的 col Test

someDatatoBePassedToRowContent


这种方法的优点是您可以将数据传递给模板并保留所有响应式优势,从而像处理 Meteor 中的任何其他模板一样处理新添加的模板。

备选方案

使用 Template.dynamic

的声明性动态模板