简体   繁体   English

在模板标记内的dom元素上添加事件侦听器

[英]adding event listener on a dom element inside template tag

Suppose I have button inside a template 假设我在模板中有按钮

<template id="persons">
     <tr>
         <td></td>
         <td></td>
         <td><button type="button" id="delete" class="btn btn-danger">Delete</button></td>
     </tr>
</template>

Now im trying to add an event listener to the button by 现在我试图通过添加一个事件监听器到按钮

this.oBtnDel = document.getElementById('delete');

this.oBtnDel.addEventListener("click", somefunc);

however im getting an error saying 但我得到一个错误说

Cannot read property 'addEventListener' of null 无法读取null的属性'addEventListener'

how can i fix this? 我怎样才能解决这个问题?

Items in templates are not part of the regular DOM. 模板中的项目不是常规DOM的一部分。 They will not be there when you are binding the event listener. 当您绑定事件侦听器时,它们不会存在。 You will also have a problem with id="delete" if you have more than one as Ids must be unique. 如果你有多个因为ID必须是唯一的,你也会遇到id="delete"的问题。

What you need to do is use event delegation , and I will use a data attribute to identify the button. 你需要做的是使用事件委托 ,我将使用数据属性来识别按钮。

Template 模板

<template id="persons">
     <tr>
         <td></td>
         <td></td>
         <td><button type="button" data-action="delete" data-objectid="id to delete" class="btn btn-danger">Delete</button></td>
     </tr>
</template>

Javascript 使用Javascript

//Bind the event to the parent table say it has an id of parentTable
this.oTable= document.getElementById('parentTable');    
this.oTable.addEventListener("click", function(event){
   //check the delete button was clicked
   if(event.target.dataset.action === "delete")
   {
       //Logic for delete goes here
       var idToDelete = event.target.dataset.objectid;
       /*Rest of your logic*/
   }
});

NOTE the code above is untested. 注意上面的代码是未经测试的。 If it doesn't work, you should be able to fill in the gaps with the links provided. 如果它不起作用,您应该能够使用提供的链接填补空白。

Further reading on event delegation: https://davidwalsh.name/event-delegate 进一步阅读事件委托: https//davidwalsh.name/event-delegate

According to MDN , 根据MDN

The HTML Content Template ( <template> ) element is a mechanism for holding HTML that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using JavaScript. HTML内容模板( <template> )元素是一种用于保存HTML的机制,该页面在加载页面时不会立即呈现,但可以在运行时使用JavaScript进行实例化。

Think of a template as a content fragment that is being stored for subsequent use in the document. 将模板视为正在存储的内容片段,以便随后在文档中使用。 While the parser does process the contents of the <template> element while loading the page, it does so only to ensure that those contents are valid; 虽然解析器在加载页面时会处理<template>元素的内容,但它只是为了确保这些内容有效; the element's contents are not rendered , however. 但是,元素的内容不会被渲染

The contents of <template> are not yet rendered when you are trying to attach an event handler to the button. 当您尝试将事件处理程序附加到按钮时,尚未呈现<template>的内容。 Try attaching the event handler after including the template to an element. 在将模板包含到元素后尝试附加事件处理程序。

See the snippet below: 请参阅下面的代码:

 var template = document.getElementById("persons"); document.body.appendChild(template.content); this.oBtnDel = document.getElementById('delete'); this.oBtnDel.addEventListener("click", () => console.log("click")); 
 <template id="persons"> <tr> <td></td> <td></td> <td><button type="button" id="delete" class="btn btn-danger">Delete</button></td> </tr> </template> 

Try like this. 试试这样吧。

 <script> 
        document.getElementById("delete").addEventListener("click", function(){ 
        // Write your function here
    }); 
        </script> 

This is return "null" error because tag is not define in HTML i convert to or any other tag ... it's solved. 这是返回“null”错误,因为标签未在HTML中定义我转换为或任何其他标签...它已解决。

<form id="persons">
    <tr>
        <td></td>
        <td></td>
        <td><button type="button" id="delete" class="btn btn-danger">Delete</button></td>
    </tr>
</form>

<script>
    function somefunc() {
        alert("hello world ...");
    }
    var oBtnDel = document.getElementById('delete');
   oBtnDel? oBtnDel.addEventListener("click", somefunc) : alert("false");
</script>

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

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