为什么记录到控制台的数据值有效,但在分配给变量时不起作用?



Javascript 新手在这里。尝试设置新的条纹结帐 V3。我需要从HTML获取一个会话ID,到Rails中的Javascript。

文件:

<%= content_tag :div, id: "temp_information", data: {temp: @session.id} do %>
<% end %>
<div data-stripe="<%= @session.id %>">
<button id="checkout-button">Pay</button>
</div>

Javascript文件:

var ses_id = $('#temp_information').data('temp');
alert(ses_id);
stripe.redirectToCheckout({
// Make the id field from the Checkout Session creation API response
// available to this file, so you can provide it as parameter here
// instead of the {{CHECKOUT_SESSION_ID}} placeholder.
sessionId: ses_id
}).then(function (result) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `result.error.message`.
});

我ses_id未定义。 当我这样做时

$('#temp_information').data('temp');

在控制台中,它显示正确的输出。但是当我这样做时:

var a = $('#temp_information').data('temp');

然后我在控制台中未定义。我在这里做错了什么? 感谢您的帮助!

$.data(parameter(用于存储信息,$.data((用于获取存储的所有数据,因此您只需删除'temp即可获取数据。

var a = $('#temp_information').data();

参考: https://api.jquery.com/data/

原来我需要使用:

$( document ).ready(function() {
*my code*
)};

等待所有内容加载,然后再尝试访问值。我认为这是因为Rails或Turbolinks。不完全确定是哪个。

最新更新