I'm going through some legacy code on a submission form and replacing JQuery w/ vanilla JS.
Right now, I have this function that uses .val() (JQuery) to grab the value for an undefined input:
myFunction: function(){
var subscription = $('input[name="subscription_id"]').val();
// Do something with subscription
}
Run Code Online (Sandbox Code Playgroud)
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'.
When I replace the JQuery with vanilla JS, like so:
myFunction: function(){
var subscription = document.querySelector('input[name="subscription_id"]').value;
// Do something with subscription
}
Run Code Online (Sandbox Code Playgroud)
And then try to run my form, I get the following error in the console:
Uncaught TypeError: Cannot read property 'value' of null
Run Code Online (Sandbox Code Playgroud)
为什么会这样呢?对此有解决方法吗?任何帮助表示赞赏。提前致谢。
这是因为
document.querySelector('input[name="subscription_id"]')
Run Code Online (Sandbox Code Playgroud)
不存在。对于香草js,您需要先检查它是否存在,然后再获取它的值。jQuery为此有一个失败的失败。
document.querySelector('input[name="subscription_id"]')
Run Code Online (Sandbox Code Playgroud)