【问题标题】:How can I get title attribute of clicked button?如何获取单击按钮的标题属性?
【发布时间】:2018-08-24 11:46:36
【问题描述】:

我正在做一个小角度项目,我的表单上有 3 个按钮,我想在点击它们时收到它们的标题。它们通常会被一一点击,到目前为止我已经尝试过:

这是我的html:

<div class="extra-btns">
  <button type="button" title="Title 1"  (click)="getMyTitleOne($event)" class="btn xbutton-square" style="font-size: 16px;"><i class="fas fa-newspaper fa-fw"></i></button>
  <button type="button" title="Title 2" (click)="getMyTitleTwo($event)" class="btn xbutton-square"><i class="fas fa-fw"></i></button>
</div>

我的打字稿代码:

  getMyTitleOne($event) {
    console.log($event.target.title);
  }

  getMyTitleTwo($event) {
    console.log($event.target.title);
  }

但在我的控制台中,有时我会得到值,有时却没有,这很奇怪,但大多数时候值是未定义的:

谢谢大家 干杯

【问题讨论】:

  • 那是因为有时 $event.target 不是按钮而是 i 标签(你的情况下的图标)。
  • 很可能您有时点击的是 标签而不是按钮

标签: javascript html css angular dom-events


【解决方案1】:

使用模板变量:

<button #button1 (click)="log(button1.title)" title="Hello, world !">Click me !</button>

Stackblitz

【讨论】:

  • 为什么button1有模板变量而button2没有?
  • 我删除了第二个按钮以免弄乱我的答案,因为您的问题是点击了错误的 HTML 元素。对此感到抱歉。
  • @Roxy'Pro 模板变量的好处是即使你点击你的图标,依然会提供标题。
  • 我没有发现需要模板变量来解决 OP 的问题,这就是我投反对票的原因
  • @JavascriptLover-SKT 您的解决方案不起作用,它给出了与原始代码相同的问题。每次我揭露你的代码问题时,请不要再苦恼了。
猜你喜欢
  • 1970-01-01
  • 2018-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-08
  • 1970-01-01
相关资源
最近更新 更多