簡體   English   中英

為什么不返回我的輸入框的值?

[英]How come my input box's value isn't being returned?

使用twitter bootstrap,我創建了一個帶有輸入框的按鈕。 我試圖使用jQuery在我的視圖中訪問該值,但是由於某種原因,除了“未定義”之外,我什么也收不到。 這是我的代碼:

jQuery的:

var browserInput = $("#browserInput").val();
console.log(browserInput);

HTML:

<div class="col-lg-4">
    <div class="input-group">
        <span class="input-group-btn">
            <button class="btn btn-primary" type="button" id="addBrowser">
            <span class="glyphicon glyphicon-plus"></span>
            Add
            </button>
        </span>
        <input id="browserInput" type="text" class="form-control" style="display: none;" >
    </div>
</div>

如果這是您的實際代碼布局,那么您將不會獲得值,因為在您請求該值時未加載DOM。

您應該嘗試將函數包裝在准備好的文檔中

$(document).ready(function() {
  var browserInput = $("#browserInput").val();
  console.log(browserInput);
});

如果您想獲得鍵盤輸入或與輸入框交互的值,也可以像

$(document).ready(function() {
 $('#browserInput').on('keyup',function() {
  var browserInput = $("#browserInput").val();
  console.log(browserInput);
});
});

我將取消刪除我的答案,因為顯然它有助於海報解決他的問題...

<input id="browserInput" type="text" value="" class="form-control" style="display: none;" />

似乎在<input>標記中具有value=""對他有所影響。

我不知道他的意思是""而不是undefined

暫無
暫無

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

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