본문 바로가기
오류 처리

form안에 button을 생성 후 onclick했지만 안됨

by dal_been 2023. 2. 23.
728x90
     <div class="container">
            <h1>Web Programming</h1>
            <p>공부할 주제를 기록해 보세요</p>
            <form action="">
                <input type="text" id="subject" autofocus>
                <button onclick="show(); ">추가</button>
            </form>
            <hr>
            <ul id="itemlist">

            </ul>
          </div>
        
       
        <script>
            
            function show(){
                let newItem=document.createElement('li');
                let text=document.querySelector('#subject');
                newItem.innerHTML=text.value;

                let item=document.getElementById('itemlist');
                item.appendChild(newItem);

                text.value="";
            }

          
        </script>

 

button을 누르면 ul밑에 li생성하려고했지만 안뜸..오류도 안뜸...

 

그런데 button onclick뒤에 return false; 넣었더니 됨..

 

왜???

일단 return false? 란 무엇일까??

ex) <a href='https://djfkdjfdk' onclick="return confirm('해당사이트로 이동?')"> 해당 사이트 </a>

confirm에서 false나오면  a의 동작을 막음(브라우저의 기본 동작을 막음)

 

 

 

그래서.. 왜 return false 넣는데..?

추측컨데... form의 동작을 막아야하는 것같다.

return false를 안넣었을때 li가 생겼다가 순식간에 사라졌다.

이부분이 form의 submit??특성때문인듯...

 

 

다른 해결책은 없는가??

form요소를 지워버리고 return false도 지웠더니 li가 생성됨

 

 

'오류 처리' 카테고리의 다른 글

자바스크립트 호출순서?(제이쿼리)  (0) 2023.03.01
parentNode와 onclick문제  (0) 2023.02.23
remove child 오류  (0) 2023.02.23