Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

javascript - 数据属性返回未定义? [等候接听](data attribute returning undefined? [on hold])

I'm trying to get the data-form-id value from the following HTML, but a console.log(formID);

(我正在尝试从以下HTML获取data-form-id值,但使用console.log(formID);)

returns undefined ?

(返回undefined ?)

Edit:

(编辑:)

My bad, the class is actually .hs-form , typo on my end.

(不好的是,我的课实际上是.hs-form ,有错字。)

 (function($) { $(document).ready(function() { var formID = $(".hs-form").data("form-id"); console.log(formID); }); })(jQuery); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form class="hs-form" data-form-id="1abe6767-4f6b-40c1-acb4-1b85bf33c932"> 

  ask by Freddy translate from so


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From jQuery .data() documentation:

(从jQuery .data()文档中:)

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

(.data()方法允许我们以一种安全的方式将任何类型的数据附加到DOM元素上,以防止循环引用,从而避免内存泄漏。)

So you need to use .attr() if you want to get the value of data-* attributes.

(因此,如果要获取data- *属性的值,则需要使用.attr() 。)

Using the data() method to update data does not affect attributes in the DOM.

(使用data()方法更新数据不会影响DOM中的属性。)

To set a data-* attribute value, use attr.

(要设置data- *属性值,请使用attr。)

Also, you don't have .hs-form in your html.

(另外,您的html中没有.hs-form 。)

If you prefer to use .data() you need to set the value first using .data( key, value )

(如果您更喜欢使用.data() ,则需要先使用.data( key, value )设置.data( key, value ))

 (function($) { $(document).ready(function() { var formID = $("form").attr("data-form-id"); console.log(formID); }); })(jQuery); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form class="form" data-form-id="1abe6767-4f6b-40c1-acb4-1b85bf33c932"> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...