我正在嘗試用普通的 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 關注
- 161 瀏覽
添加回答
舉報
0/150
提交
取消