我想觸發自定義元素中所有屬性的內容<my-component>。目前只執行前面的屬性。
如果它有效,這將是<p>hello, world! welcom </p>.
另外,我希望在有或沒有空格的情況下執行 {{ }} 部分。
function component(elementName, ComponentOptions) {
customElements.define(`${elementName}`, class extends HTMLElement {
connectedCallback() {
if (ComponentOptions.return) {
if (this.getAttributeNames()) {
const AttrNames = this.getAttributeNames();
var optionsreturn = ComponentOptions.return;
AttrNames.forEach(attr => {
let val = this.getAttribute(attr);
optionsreturn = optionsreturn.replace(`{{ ${attr} }}`, val);
this.outerHTML = optionsreturn;
});
} else {
this.outerHTML = ComponentOptions.return
}
}
}
});
}
component("my-component", {
return: `<p>hello, {{ w }} {{ wel }} </p>`
})
<my-component w="world!" wel="welcom"></my-component>
uj5u.com熱心網友回復:
您需要將您的移動到回圈this.outerHTML = optionsreturn;之外。forEach
我還在您的.replace()通話中將字串更改為正則運算式。它現在將接受圍繞您的屬性名稱的零個或一個空格。
function component(elementName, ComponentOptions) {
customElements.define(elementName, class extends HTMLElement {
connectedCallback() {
if (ComponentOptions.return) {
if (this.getAttributeNames()) {
const AttrNames = this.getAttributeNames();
var optionsreturn = ComponentOptions.return;
AttrNames.forEach(attr => {
let val = this.getAttribute(attr);
optionsreturn = optionsreturn.replace(new RegExp(`\{\{ ?${attr} ?\}\}`,"g"), val);
});
this.outerHTML = optionsreturn;
} else {
this.outerHTML = ComponentOptions.return
}
}
}
});
}
component("my-component", {
return: `<p>hello, {{ w }} {{wel}} </p>`
})
<my-component w="world!" wel="welcom"></my-component>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/419506.html
標籤:
