2010-08-31 6 views
10

c'est le code de démonstration:comment obtenir toutes les données qui stockées dans jquery.data()

$(document).ready(function(){ 

    $("button").click(function(e) { 
     var value; 

     switch ($("button").index(this)) { 
     case 0 : 
      value = $("div").data("blah"); 
      break; 
     case 1 : 
      $("div").data("blah", "hello"); 
      value = "Stored!"; 
      break; 
     case 2 : 
      $("div").data("blah", 86); 
      value = "Stored!"; 
      break; 
     case 3 : 
      $("div").removeData("blah"); 
      value = "Removed!"; 
      break; 
     } 

     $("span").text("" + value); 
    }); 

    }); 
    </script> 
    <style> 
    div { margin:5px; background:yellow; } 
    button { margin:5px; font-size:14px; } 
    p { margin:5px; color:blue; } 
    span { color:red; } 
    </style> 
    <div>A div</div> 
    <button>Get "blah" from the div</button> 
    <button>Set "blah" to "hello"</button> 
    <button>Set "blah" to 86</button> 
    <button>Remove "blah" from the div</button> 
    <p>The "blah" value of this div is <span>?</span></p> 

mais, comment obtenir toutes les données (car un nom clé que je ne sais pas) ??

grâce

Répondre

27

Vous pouvez appeler .data()sans aucun argument pour obtenir tout un objet avec toutes les entrées, comme ceci:

$("div").data() //returns object 

Cet objet aura tous ils clés disponibles, par exemple, si :

$("div").data("thing") //returns "value" 

Puis $("div").data() retourneraient au moins:

{ thing: "value" } 
Questions connexes