[英]JQuery in Rails app Uncaught ReferenceError: variable is not defined
I am building a Shopping Application with Rails and jQuery. 我正在使用Rails和jQuery构建购物应用程序。 Rails Version 5.1.6.
Rails版本5.1.6。 I have an inventories controller and the corresponding inventories.js.
我有一个库存控制器和相应的inventories.js。
inventories.js inventories.js
document.addEventListener("turbolinks:load", function() {
function add_item_to_cart(target_elem) {
item = $(target_elem).closest('.grid-item')[0].dataset;
quantity = $(target_elem).next().val();
// and some operation wih the quantity element and item.
}
$('.add-to-cart').on('click',function(){
add_item_to_cart(this);
})
})
The problem is whenever I do $(target_elem).next().val() from console I am getting the value from the quantity input box corectly. 问题是每当我从控制台执行$(target_elem).next()。val()时,我都会从数量输入框中获取值。 But when I execute the jquery inventories.js it says
但是当我执行jquery inventories.js时,它说
Uncaught ReferenceError: quantity is not defined
at add_item_to_cart (inventories.self-65782850f63f3dad515dba7e67e72a65016e58fb0751ff2f6342d4183d7d2a0e.js?body=1:10)
at HTMLButtonElement.<anonymous> (inventories.self-65782850f63f3dad515dba7e67e72a65016e58fb0751ff2f6342d4183d7d2a0e.js?body=1:54)
at HTMLButtonElement.dispatch (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:5227)
at HTMLButtonElement.elemData.handle (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:4879)
Also my jquery always returns something like jQuery.fn.init when selecting an element using a selector. 同样,当使用选择器选择元素时,我的jquery总是返回类似jQuery.fn.init的信息。 Is this an expected behaviour?
这是预期的行为吗? because I have not faced anything like this before.
因为我以前从未遇到过这样的事情。
item = $(target_elem).closest('.grid-item')
jQuery.fn.init [div.grid-item, prevObject: jQuery.fn.init(1), context: button.add-to-cart]
In my Gemfile 在我的Gemfile中
gem 'jquery-rails'
gem 'jquery-turbolinks'
The behaviour is right, in the javascript
you need to denote variable with var
or const
or let
: 行为是正确的,在
javascript
您需要使用var
或const
或let
来表示变量:
var quantity = $(target_elem).next().val();
Otherwise it is undefined variable. 否则,它是未定义的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.