簡體   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