简体   繁体   English

HTML中的`#`属性有什么作用?

[英]What does a `#` attribute do in HTML?

I am writing a handler to do something to some element when a user clicks on a different element. 当用户点击不同的元素时,我正在编写一个处理程序来对某个元素执行某些操作。

At first I had the following (This is using Angular2 but I suspect the only different is how the onclick event is handled): 起初我有以下内容(这是使用Angular2,但我怀疑唯一不同的是如何处理onclick事件):

        <span>
            <input type="text" id="bioName">
        </span>
        <span class="icon-pencil" (click)="editField(bioName);"></span>

...but this didn't work. ......但这没效果。 I then found an example that identified the input field differently, and this did work for me. 然后我找到了一个以不同方式识别输入字段的示例,这对我有用。 It was as follows: 它如下:

        <span>
            <input type="text" #bioName>
        </span>
        <span class="icon-pencil" (click)="editField(bioName);"></span>

Unfortunately I can't find anything that explains this. 不幸的是我找不到任何解释这个的东西。 Searching for "hash" and "pound" with HTML and Javascript yield too many results that have nothing to do with this in the subject area. 使用HTML和Javascript搜索“hash”和“pound”会产生太多结果,这些结果与主题领域中的内容无关。

So what does # do in this case? 那么在这种情况下#做什么? Can id not be used to obtain a reference to the DOM element when setting up an event handler? 在设置事件处理程序时,是否可以使用id来获取对DOM元素的引用? What is this called so I can google it and read the appropriate documentation? 这叫什么,所以我可以google它并阅读相应的文档?

This is Angular2 specific, regular HTML doesn't recognize this syntax, ie you have to use id="bioName" in order to access the tag with CSS/JavaScript. 这是Angular2特定的,常规HTML无法识别此语法,即您必须使用id="bioName"才能使用CSS / JavaScript访问该标记。

Here is more information on how to use # in Angular2. 以下是有关如何在Angular2中使用#更多信息。

Hash ( # ) is syntax for defining template variable in Angular 2 templates. 散列( # )是在Angular 2模板中定义模板变量的语法。 It is used to assign unique identifiers to template elements which you can later use to get a reference to template elements in component. 它用于为模板元素分配唯一标识符,您可以在以后使用它来获取对组件中模板元素的引用。 In your case, for example, you can use bioName variable to get a reference to input element in your component and you can do whatever you want with it there - get file name, file size or even file itself. 例如,在您的情况下,您可以使用bioName变量来获取组件中输入元素的引用,您可以随意执行任何操作 - 获取文件名,文件大小甚至文件本身。 This is done using ViewChild decorator. 这是使用ViewChild装饰器完成的 You can check out answer I wrote few days ago and see what template variables are mostly used for. 您可以查看我几天前写的答案 ,看看主要用于哪些模板变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM