繁体   English   中英

如何从javascript中的输入文本中获取价值

[英]how to get value out of input text in javascript

我正在尝试获取userinput的值,但是我的代码无法正常工作。

html

<body>
<button id="test">test</button>
<form>
    <input type="text" id="test1">
</form>
</body>

javascript:

var text = null;

$(document).ready(function(){
    text = $("#test1").value;
    $("#test").on("click", testing);

});

function testing(){
    console.log("something");
    if(text == "top"){
        console.log("top");
    }
}

在jQuery中,它是val() ,而不是value ,仅适用于本机DOM节点

text = $("#test1").val();

而且这里确实不需要全局变量,并且您应该确保在单击按钮时更新了该值,现在它仅存储在DOM上。

$(document).ready(function(){
    $("#test").on("click", testing);
});

function testing(){
    var text = $("#test1").val();

    if(text == "top"){
        console.log("top");
    }
}

您可以使用val()

text = $("#test1").val();

另外,您还需要在testing功能内的行上方移动,以使其在单击按钮时检查您输入的值。 因此最终代码如下所示:

var text = null;

$(document).ready(function(){
    $("#test").on("click", testing);
});

function testing(){
    console.log("something");
    text = $("#test1").val();
    if(text == "top"){
        console.log("top");
    }
}

小提琴演示

只是这会工作

$("#test").click(function(){
     var value = $("#test1").val();
     alert(value); check value by alert
});

您可以在jQuery中使用.val()方法

演示

 text = $("#test1").val();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM