我需要了解表单提交如何从自定义Web组件中提取数据?
我尝试了以下步骤
1-将输入附加到ShadoWroot
2-利用表单关联的概念将输入值和名称与表单联系起来
3-最后我提交表单以获得FormData
。
不幸的是,它没有成功。我从FormData
中什么也得不到
// https://web.dev/more-capable-form-controls/
// https://webkit.org/blog/13711/elementinternals-and-form-associated-custom-elements/
// https://html.spec.whatwg.org/#custom-elements
let form = document.getElementById('frm');
// on form submit I need to recive form data from the input by getting name and its value
form.addEventListener('submit', (event) => {
event.preventDefault();
var formData = new FormData(form);
// Display the key/value pairs
for (const pair of formData.entries()) {
console.log(`${pair[0]}, ${pair[1]}`);
}
});
// I need here to assign value to form data using input name and input value
class SomeTextFieldElement extends HTMLElement {
static formAssociated = true;
internals;
shadowRoot;
constructor()
{
super();
this.internals = this.attachInternals();
this.shadowRoot = this.attachShadow({mode: 'closed', delegatesFocus: true});
this.shadowRoot.innerHTML = "<input name='test' autofocus>";
const input = this.shadowRoot.querySelector('input');
input.addEventListener('change', () => {
this.internals.setFormValue(input.value, input.value);
});
}
formStateRestoreCallback(state, reason)
{
this.shadowRoot.querySelector('input').value = state;
}
}
customElements.define('some-text-field', SomeTextFieldElement);
<form id='frm'>
<some-text-field></some-text-field>
<button type="submit">Submit</button>
</form>
1条答案
按热度按时间cu6pst1q1#
@Danny在评论中发布的链接有正确的答案。(感谢发布。)因此,下面的代码片段不是我的代码,而是来自链接的www.example.com文章中的示例代码。我已经将其合并到您原始帖子中的代码示例中。web.dev article. I've incorporated it into your code sample from your original post.
我注解掉了一些不影响将定制组件的输入值插入表单数据的函数,这样就可以清楚地看到哪些函数参与表单数据插入过程。