簡體   English   中英

(DOM 問題)不返回任何內容

[英](DOM issue) not returning anything

我是 JavaScript 新手,當用戶單擊 ID 為"push"的按鈕並將其更改為 input class="inputV"的值時,我試圖操作類為“text”的 HTML h2元素的值class="inputV" ,但是我注意到當輸入字段中沒有值時,整個塊就會消失,所以如果輸入不正確,我試圖返回一個不同的值! 那我該怎么做呢! 這就是我到目前為止所嘗試的。

    function input(){
    var inputValue= document.getElementById('inputV').value;
    var text = document.querySelector('.text').textContent;

    if (inputValue){
            text = inputValue;
            }else{
                text = 'Null';
        }
        return text;
    };

    document.getElementById('push').addEventListener('click',input);



    <div class=container><h1>JavaScript OOP</h1>
            <div>
                <form class="input">
                    <input id="inputV" type="text" name="name" placeholder="Enter your Name">
                </form>
            </div>
            <div><h2 class="text">Results</h2></div>
            <button id="push" value="Sign me in" onclick="input()">Sign me in</button>
        </div>

不需要初始化text ,只需聲明即可。
將您的return text替換為<h2>分配,如下所示

function input(){
    var inputValue= document.getElementById('inputV').value;
    //var text = document.querySelector('.text').textContent;
    var text;

    if (inputValue){
        text = inputValue;
    }
    else{
        text = 'Null';
    }
    // return text;
    document.querySelector('.text').textContent = text;
}

document.getElementById('push').addEventListener('click',input);

為按鈕設置onclick="input()" ,您無需額外定義事件偵聽器。 你也可以讓函數體更短一點

 function input(){ var inputValue= document.getElementById('inputV').value; var text = document.querySelector('.text'); text.textContent = inputValue || 'Null'; }; // document.getElementById('push').addEventListener('click',input);
 <div class=container><h1 class="text">JavaScript OOP</h1> <div> <form class="input"> <input id="inputV" type="text" name="name" placeholder="Enter your Name"> </form> </div> <div><h2 class="text">Results</h2></div> <button id="push" value="Sign me in" onclick="input()">Sign me in</button> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM