jquery hasData() method


  Translation results:

has

英[həz] 美[hæz]  

v.Have (the third person singular of have); (in a kinship relationship) accept; take; Buy

data

English [ˈdeɪtə] US [ˈdetə, ˈdætə, ˈdɑtə]

n. Information, material; plural of datum;[ computer] data, information; value extracted from scientific experiments

jquery hasData() methodsyntax

Function: hasData() method detects whether the element has any jQuery data related to it.

Syntax: jQuery.hasData(element)

Parameters:

ParameterDescription
element Optional. The DOM element whose data needs to be inspected.

Description: jQuery.hasData() method detects whether the element currently has any value set by using jQuery.data(). This method returns false if no data is associated with the element (no data object exists at all or the data object is empty); otherwise it returns true. The main advantage of jQuery.hasData(element) is that a data object is not created and associated with an element if one does not exist. In contrast, jQuery.data(element) always returns the data object to the caller, or creates it if it did not previously exist.

jquery hasData() methodexample

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
</head>

<body>

<p>结果:</p>

<script>
$(function(){
  var $p = jQuery("p"), p = $p[0];
  $p.append(jQuery.hasData(p)+" "); /* false */
  jQuery.data(p, "testing", 123);
  $p.append(jQuery.hasData(p)+" "); /* true*/
  jQuery.removeData(p, "testing");
  $p.append(jQuery.hasData(p)+" "); /* false */
});
</script>

</body>
</html>
Run instance »

Click the "Run instance" button to view the online instance

Home

Videos

Q&A