英文:
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
<input type="text" value="somevalue" {{on "click" this.updatevalue}}/>
<button type="button" id="test">test</button>
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>
这里有一个在线演示
参考资料:
- https://tutorial.glimdown.com
- https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
- https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
- https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
- https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event
- https://developer.mozilla.org/en-US/docs/Web/API/Event/target
英文:
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
}
<button type="button" {{on 'click' this.handleClick}}>test</button>
Here is a live demo
References:
- https://tutorial.glimdown.com
- https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
- https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
- https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
- https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event
- https://developer.mozilla.org/en-US/docs/Web/API/Event/target
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论