简体   繁体   English

用 JS.value 替换 JQuery.val()

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

I'm going through some legacy code on a submission form and replacing JQuery w/ vanilla JS.我正在查看提交表单上的一些遗留代码,并用 vanilla JS 替换 JQuery。

Right now, I have this function that uses.val() (JQuery) to grab the value for an undefined input:现在,我有这个 function 使用.val() (JQuery) 来获取未定义输入的值:

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

When I run the code in my browser, I get no issues - the code is meant to work only if a subscription is passed into the input - if it's not there, we just get an undefined value.当我在浏览器中运行代码时,我没有遇到任何问题——代码只有在订阅被传递到输入时才能工作——如果它不存在,我们只会得到一个未定义的值。 The value returned by the JQuery combo of $() and.val() console logs to 'undefined'. $() 和 .val() 控制台的 JQuery 组合返回的值记录到“未定义”。

When I replace the JQuery with vanilla JS, like so:当我用香草JS替换JQuery时,像这样:

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

And then try to run my form, I get the following error in the console:然后尝试运行我的表单,我在控制台中收到以下错误:

Uncaught TypeError: Cannot read property 'value' of null

Why is this happening?为什么会这样? And is there a workaround for this?有没有解决方法? Any help is appreciated.任何帮助表示赞赏。 Thanks in advance.提前致谢。

This happens because发生这种情况是因为

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

does not exist.不存在。 For vanilla js, you need to check if it exists first, then get the value if it does.对于vanilla js,你需要先检查它是否存在,如果存在则获取值。 jQuery has a silent fail for this. jQuery 对此有一个无声的失败。

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

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

Just use a condition:只需使用一个条件:

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