我正在尝试用普通的 Javascript 模拟表单的数据输入。我无法操作 HTML。我的代码工作正常,直到单击最后的保存按钮,然后清除填写的输入。如何填写输入并确保单击最后的“保存”按钮时数据不会被清除?HTML:<input placeholder="What is the title" maxlength="50" type="text" data-vv-name="title" aria-label="form__text" class="form__text p--4" aria-required="true" aria-invalid="false"><textarea placeholder="Describe it! (required)" maxlength="500" data-vv-name="description" aria-label="form__text" class="form__text listing-editor__description__input p--3" aria-required="true" aria-invalid="false" style="height: 135px;"></textarea>JavaScript:if (document.querySelectorAll('.p--4')[0]) { document.querySelectorAll('.p--4')[0].value = "Wuthering Heights by Emily Brontë"; document.querySelector('.p--4').dispatchEvent(new Event('change', { 'bubbles': true }));}if (document.querySelectorAll('.p--3')[0]) { document.querySelectorAll('.p--3')[0].value = "Wuthering Heights is a novel by Emily Brontë published in 1847 under her pseudonym Ellis Bell. Brontë's only finished novel, it was written between October 1845 and June 1846. Wuthering Heights and Anne Brontë's Agnes Grey were accepted by publisher Thomas Newby before the success of their sister Charlotte's novel Jane Eyre. After Emily's death, Charlotte edited the manuscript of Wuthering Heights and arranged for the edited version to be published as a posthumous second edition in 1850."; document.querySelector('.p--3').dispatchEvent(new Event('change', { 'bubbles': true }));}
1 回答
慕虎7371278
TA贡献1802条经验 获得超4个赞
您的代码示例似乎不完整,但我假设这些元素位于元素内部form,按钮是button带有 的元素type="submit",并且按钮位于表单内部。
如果您想阻止提交按钮发布表单,那么您需要阻止默认行为:
const form = document.querySelector('form');
form.addEventListener('submit', (event) => {
event.preventDefault();
console.log('Do stuff here...');
});
<form>
<button type="submit">Submit</button>
</form>
- 1 回答
- 0 关注
- 98 浏览
添加回答
举报
0/150
提交
取消