从内联元素访问 Web 组件中的类函数 [英] Access class function in Web Component from inline Element
问题描述
我想从我的 Web 组件中的元素执行定义的类函数:
I want to execute a defined class function from an Element inside my Web Component:
customElements.define('first-component', class FirstComponent extends HTMLElement {
constructor() {
super();
}
log() {
console.log('Well Done!')
}
connectedCallback() {
this.innerHTML = '<button onclick="log()">Do it</button>'
}
});
现在状态:ReferenceError:未定义日志
推荐答案
With parentElement, or Nearest()
为了调用自定义元素的 log()
方法,您必须获得它的引用.
In order to call the log()
method of the custom element, you'll have to get a reference on it.
在您的示例中,自定义元素是 元素的父元素,因此您应该调用按钮的
parentElement
属性,如已说明的@Smankusors:
In your example, the custom element is the parent element of the <button>
element, so you should call the parentElement
property of the button as already stated by @Smankusors:
<button onclick="this.parentElement.log()>Do it</button>
<小时>
使用 getRootNode()
或者,在更复杂的 DOM 树中,如果使用 Shadow DOM,您可以使用 getRootNode()
结合 host
来获取自定义元素引用.
Alternately, in a more complex DOM tree, and if a Shadow DOM is used, you can use getRootNode()
combined with host
to get the custom element reference.
customElements.define('first-component', class FirstComponent extends HTMLElement {
log() {
console.log('Well Done!')
}
connectedCallback() {
this.attachShadow({mode: 'open'})
.innerHTML = '<button onclick="this.getRootNode().host.log()">Do it</button>'
}
})
<first-component></first-component>
具有唯一标识符
您还可以通过其 id
属性(如果有)调用自定义元素:
You can also call the custom element by its id
property (if it has one) :
customElements.define('first-component', class FirstComponent extends HTMLElement {
log() {
console.log('Well Done!')
}
connectedCallback() {
if (!this.id)
this.id = "_id"
this.innerHTML = `<button onclick="${this.id}.log()">Do it</button>`
}
})
<first-component></first-component>
使用 handleEvent()
出于安全原因,您可以避免内联脚本并实现 handleEvent()
方法,然后根据某些条件在其中调用特定方法:
For security reasons, you can avoid inline script and implement the handleEvent()
method, then call inside it a specific method depending on some criterions :
customElements.define('first-component', class FirstComponent extends HTMLElement {
log() {
console.log('Well Done!')
}
handleEvent(ev) {
if (ev.target.innerText == 'Do it')
this.log()
}
connectedCallback() {
this.innerHTML = '<button>Do it</button>'
this.addEventListener('click', this)
}
})
<first-component></first-component>
这篇关于从内联元素访问 Web 组件中的类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!