简体   繁体   English

(DOM 问题)不返回任何内容

[英](DOM issue) not returning anything

I'm new to JavaScript and I was trying to manipulate the value of an HTML h2 element with the class of "text" when the users clicks on the button with the id "push" and change it to the value of the input class="inputV" , however i noticed that when there's no value in the input field the whole block just disappears so I tried to return a different value if the input is not true!我是 JavaScript 新手,当用户单击 ID 为"push"的按钮并将其更改为 input class="inputV"的值时,我试图操作类为“text”的 HTML h2元素的值class="inputV" ,但是我注意到当输入字段中没有值时,整个块就会消失,所以如果输入不正确,我试图返回一个不同的值! so how do i go out about doing this!那我该怎么做呢! that's what I've tried so far.这就是我到目前为止所尝试的。

    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>

Initialization of text is not needed, just declare it.不需要初始化text ,只需声明即可。
Replace your return text with assignment to <h2> as below将您的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);

Once you set onclick="input()" for the button you don't need to extra define an event listener.为按钮设置onclick="input()" ,您无需额外定义事件侦听器。 Also you can make the function body a bit shorter你也可以让函数体更短一点

 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