【问题标题】:How to search an Event to get the name of an Element?如何搜索事件以获取元素的名称?
【发布时间】:2018-09-16 21:23:15
【问题描述】:

假设我的组件中有一个剪贴板粘贴事件,如下所示。

window.addEventListener('paste', this.insertNewRowsBeforePaste.bind(this));

然后当我按下键盘上的 ctrl + V 时,它会调用此事件,即 ClipboardEvent

insertNewRowsBeforePaste(event) {   
const tabName = // <---- I need to be able to see which tab the user has clicked on then I can do other processing based on the current tab.
}

所以我希望它说 tabName = 'Tab 1' 或 'Tab 2' 等,因为我的组件是一个带有多个选项卡的选项卡控件。

【问题讨论】:

    标签: html typescript dom


    【解决方案1】:

    EventTarget event.target 将提供触发事件的HTMLElement。然后,您可以将name 属性定位到&lt;button&gt;&lt;input&gt;&lt;a&gt; 等元素上。您还可以访问其他属性,例如 innerHTMLtextContent 以进行检查。

    insertNewRowsBeforePaste(event) {   
        const target = event.target;
        const name = target.name; 
    
        console.log(name);
    
        if (name.indexOf('Tab 1') > -1) { console.log('Tab 1'); }
    }
    

    这是一个example 使用event.target 的单击元素来访问它们各自的nameinnerHTMLtextContent 属性值。

    如果您在 TypeScript 中执行此操作,则需要在 target 上使用强制转换/类型断言来访问 HTMLButtonElement | HTMLInputElement | HTMLAnchorElement 属性,例如 name

    insertNewRowsBeforePaste(event) {
        const target = event.target as HTMLButtonElement;
        const name = target.name;
    
        // or
        // const name = (<HTMLButtonElement> event.target).name;
    
        // or
        // const target = event.target as HTMLButtonElement;
        // const { name } = target;        
    }
    

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多