e.preventDefault();在我的模块表单中不起作用,我尝试了一切但找不到解决方案

问题描述 投票:0回答:2

有人可以帮助我吗?

preventDefault()
不工作,我尝试 addEventListener('click' 或 'submit') 如果我把 click required 不工作但如果我把 submit preventDefault 不工作我到处找但能找到类似的问题。

<div class="modals">
        <div class="pls">
        <h2>Add Book</h2>
        <!-- Trigger/Open The Modal -->
        <button id="myBtn">+</button>
        </div>
        <!-- The Modal -->
        <div id="myModal" class="modal">
        
          <!-- Modal content -->
          <div class="modal-content">
            <span class="close">&times;</span>
            <div class="book hidden">
                <form action="#" class="bookTag" method="get">
                    <input type="text" id="title" name="title" placeholder="Title" required/>
                    <input type="text" id="author" name="author" placeholder="Author" required/>
                    <input type="number" id="pages" name="pages" placeholder="Pages" required/>
                   <div class="readed">
                        <label for="read">Have you read it?</label>
                        <input type="checkbox" name="read" id="read" />
                   </div>
                    <button  type="submit" id="add">Add</button>
                </form>
            </div>
          </div>
        </div>
    </div>
button.addEventListener('submit',function(e){
    console.log("heADSFASDGDGDFGADFHDGDAj")
    myLibrary[x] = new book (title.value, author.value, pages.value, read.value);
    addbook(title.value, author.value, pages.value, x, read);
    x = x +1;
    title.value = author.value = pages.value = "";
    e.preventDefault();
    modal.style.display = "none";
})



(I DONT KNOW IF THIS HELPS THIS IS FOR MODULE POP UP)

// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
javascript forms module submit preventdefault
2个回答
0
投票

这是带有完整代码的github链接

https://github.com/Kukii258/Library-.git


-1
投票

将 e.preventDefault() 放在事件监听器的开头。

    button.addEventListener('submit',function(e){
    e.preventDefault();
    console.log("heADSFASDGDGDFGADFHDGDAj")
    myLibrary[x] = new book (title.value, author.value, pages.value, read.value);
    addbook(title.value, author.value, pages.value, x, read);
    x = x +1;
    title.value = author.value = pages.value = "";
    modal.style.display = "none";
})

© www.soinside.com 2019 - 2024. All rights reserved.