簡體   English   中英

用 JS.value 替換 JQuery.val()

[英]Replacing JQuery .val() with JS .value

我正在查看提交表單上的一些遺留代碼,並用 vanilla JS 替換 JQuery。

現在,我有這個 function 使用.val() (JQuery) 來獲取未定義輸入的值:

myFunction: function(){
          var subscription = $('input[name="subscription_id"]').val();
          // Do something with subscription
}

當我在瀏覽器中運行代碼時,我沒有遇到任何問題——代碼只有在訂閱被傳遞到輸入時才能工作——如果它不存在,我們只會得到一個未定義的值。 $() 和 .val() 控制台的 JQuery 組合返回的值記錄到“未定義”。

當我用香草JS替換JQuery時,像這樣:

myFunction: function(){
          var subscription = document.querySelector('input[name="subscription_id"]').value;
          // Do something with subscription
}

然后嘗試運行我的表單,我在控制台中收到以下錯誤:

Uncaught TypeError: Cannot read property 'value' of null

為什么會這樣? 有沒有解決方法? 任何幫助表示贊賞。 提前致謝。

發生這種情況是因為

document.querySelector('input[name="subscription_id"]')

不存在。 對於vanilla js,你需要先檢查它是否存在,如果存在則獲取值。 jQuery 對此有一個無聲的失敗。

var element = document.querySelector('input[name="subscription_id"]');

// If it exists, return its value, or null
var subscription = element ? element.value : null;

只需使用一個條件:

var elem = document.querySelector('input[name="subscription_id"]');
var subscription = elem ? elem.value : "";

暫無
暫無

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

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