meteor.js:如何访问 HTML 元素的值

meteor.js: How to access value of HTML-element

使用meteor.js框架,如何在"meteor way"中选择HTML元素的值?通过使用 jQuery 选择器,浏览器会为每个项目遍历 DOM,这是非常昂贵的,不是吗?

流星教程使用提交表单并在 onSubmit 事件中处理模板变量。但是,如果没有 onSubmit(因此没有包含相关元素的模板变量),它是如何完成的?

有人可以帮忙给出下面的例子吗?

cars.html

<template name="Car">
    <div class="car-item" contenteditable="true">BMW</div>
    <div class="edit-bar"><a href="#" class="save">save</a></div>
</template>

cars.js

'click .save'(event, template){
    //access content of '.car-item' here when '.save' is clicked
}

尝试将名称添加到您的 div

<div class="car-item" contenteditable="true" name="car">

然后在你的点击事件中:

click.save(event, template){

   var car = event.target.car.value;
}

让我们知道它是否有效。

可以使用template instance's jQuery。它将仅作用于当前模板的元素:

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.

这会带来更高的性能,但需要您控制要搜索的元素的粒度和范围。

选择器范围示例

只需比较以下示例的输出:

'click .save'(event, templateInstance){
    //access content of '.car-item' here when '.save' is clicked

    // global scope search
    console.log($('div'));

    // template scope search
    console.log(templateInstance.$('div'));
}

已应用于您的代码

它产生以下代码:

'click .save'(event, templateInstance){
    // access content of '.car-item' here when '.save' is clicked
    const carItems = templateInstance.$('.car-item');
    // ... process car items
}