簡體   English   中英

使用 jQuery 將文本框中的值提供給變量

[英]Feeding a value from a textbox to a variable using jQuery

我有一個名為“myLocation”的變量。

我想從我的文本框中獲取值並將其輸入到變量“myLocation”內的“lat1”中。

我曾嘗試使用 jQuery $().attr('value')函數,但它似乎不起作用。

有什么建議?

這是我的代碼:

<input type="text" id="input1">

$(document).ready(function () {
    $('#input1').keypress(function(event) {
        if (event.which == 13) {
            element1 = $('#input1').attr('value');

            var myLocation = {
                lat1: 2, // I wold like to feed data here from the textbox
                         // I tried element1 = $('#input1').attr('value'); but it does
                            not seem to work
                lng2: -56
            };
        };
    });
});

它是您函數中的 $('#input1').val() 或 $(this).val() 。

 $(document).ready(function () { $('#input1').keypress(function( event ) { if ( event.which == 13 ) { element1 = $(this).val(); console.log("Element 1: ", element1); var myLocation = { lat1: $(this).val(), lng2: -56 }; }; }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type = "text" id = "input1">

改變

element1 = $('#input1').attr('value');

element1 = $(this).val();  // 'this' refers to the input element itself, benefit is that it wont refetch; val() will get the value

閱讀: .attr() | jQuery API 文檔


工作代碼片段:

 $(document).ready(function() { $('#input1').keypress(function(event) { if (event.which == 13) { var element1 = $('#input1').val(); // make sure to initialize using "var" or else element1 will be a global variable! var myLocation = { lat1: element1, lng2: -56 }; console.log('myLocation', myLocation); // verify it in your log! }; }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="input1">

暫無
暫無

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

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