如何在Ember 4.12控制器中访问DOM。

huangapple go评论55阅读模式
英文:

how to access dom in ember 4.12 controller

问题

在控制器中如何访问测试按钮并更改其标题?

test.hbs

<input type="text" value="somevalue" {{on "input" this.updateValue}}/>
<button type="button" id="test">test</button>

test.js

import Controller from '@ember/controller';
import { action } from '@ember/object';

export default class TestController extends Controller {
  @action
  updateValue(event) {
    // 获取测试按钮并更改其标题
    const testButton = document.getElementById('test');
    if (testButton) {
      testButton.innerText = event.target.value;
    }
  }
}
英文:

I have a input box in DOM, and monitor the input value in controller, and there's another button, if the input value is changed, I want to change the button title or properties accordingly, how can I do this in controller?

test.hbs

&lt;input type=&quot;text&quot; value=&quot;somevalue&quot; {{on &quot;click&quot; this.updatevalue}}/&gt;
&lt;button type=&quot;button&quot; id=&quot;test&quot;&gt;test&lt;/button&gt;

test.js

  @action
  updatevalue(value) {
    //how to access test button, and change its title?
  }

答案1

得分: 1

on 修饰符是 addEventListener / removeEventListener 的简写形式,因此在按钮上使用 on 后,单击按钮时,事件处理程序会接收到一个 MouseEvent

所以,

  @action
  handleClick(event) {
    event.target // 按钮
  }

  @action
  updatevalue(event /* 不是 value */) {
    event.target // 输入框
  }
<button type="button" {{on 'click' this.handleClick}}>测试</button>

这里有一个在线演示

参考资料:

英文:

the on modifier is short for addEventListener / removeEventListener, so clicking the button, once on is used on the button, the event handler receives a MouseEvent

So,

  @action
  handleClick(event) {
    event.target // the button
  }

  @action
  updatevalue(event /* not value */) {
    event.target // the input
  }
&lt;button type=&quot;button&quot; {{on &#39;click&#39; this.handleClick}}&gt;test&lt;/button&gt;

Here is a live demo

References:

huangapple
  • 本文由 发表于 2023年6月16日 11:56:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76486879.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定