2017-06-29 105 views
0

正如你所看到的,我有不止一個data-record-*屬性,並且我想通過jQuery的幫助獲得這些屬性在每個函數中使用的值。如何獲取屬性值?

但我想用jquery自動獲取這些值,例如屬性以``data-record`開頭。

,我將發佈與jQuery/AJAX這些值

$('a').on('click',function(){ 
 
    var el = $(this).data(); 
 
    el.each(function(e){ 
 
    alert(el); 
 
    }) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#" data-record-id="1" data-record-name="section-1" data-record-order="short" class="ajax">Click on me!</a>

+0

我很困惑你問一點點:S – ThisGuyHasTwoThumbs

+0

我有我的錨鏈接屬性我想要獲得每個函數的這個屬性的值:) –

+0

似乎你需要一個過濾的屬性列表。檢查[this](https://stackoverflow.com/questions/4187032/get-list-of-data-attributes-using-javascript-jquery) –

回答

1

就消除環路;我認爲這是你要找的東西?

$('a').on('click',function(){ 
 
    
 
    var TheData = $(this).data(); 
 

 
    for (var key in TheData) { 
 

 
    console.log(TheData[key]); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#" data-record-id="1" data-record-name="section-1" data-record-order="short" class="ajax">Click on me!</a>

+0

如果我使用這樣的: '$('a')。on ('click',function(){ var el = $(this).data(); alert(el) });'這個返回對象對象我需要一個一個的alert或with在列表項中doesn無論如何我會用ajax發佈這些數據,這就是爲什麼我要求 –

+0

好的,那麼看到更新的答案;一旦你獲得了對象中的數據,只需循環鍵。嘗試一下;有用。 – frenchie

+0

工作得很好,所以我會嘗試用ajax這個值是可能的一個接一個? ('click',function(){var myData = $(this).data(); $ .each(myData,function(index,value){{'a')。 (「ul」)。append(「

  • 」+「index:」+ index +「value:」+ value +「
  • 」); $ .ajax({ url:value, method:「post」 成功:功能(數據){ } }); }}; }); ' –

    1

    改變了每一個函數調用到jquery.each() - jQuery的文檔以下的.OBJ()

    $('a').on('click',function(){ 
        var myData = $(this).data(); 
        jQuery.each(myData, function(index, value) { 
        alert("index: " + index + "value: " + value); 
    }); 
    }); 
    

    只是閱讀更多關於它的工作方式在這裏:https://api.jquery.com/Types/#Object

    +0

    偉大的,因爲我想要感謝你 –

    +0

    我有一個問題,我們可以讓這個'myData'變量開始與'data-records-'? –

    +0

    nope - jquery .data()自動將html5.0數據屬性映射爲基於駱駝的名稱。有關詳細信息,請參閱https://api.jquery.com/data/#data-html5 – errand

    0

    這將爲您提供您可以在UR Ajax調用中使用的JSON對象。另外,您可以替換鍵前綴以及與「key.replace」

    $('a').on('click',function(){ 
     
        
     
        var TheData = $(this).data(); 
     
        var TheJson = ""; 
     
        for (var key in TheData) { 
     
        TheJson+='"'+ key+'":"'+TheData[key]+'",';   
     
        } 
     
        TheJson="{"+TheJson.substr(0,TheJson.length-1)+"}"; 
     
        console.log(JSON.parse(TheJson)); 
     
        
     
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
     
    <a href="#" data-record-id="1" data-record-name="section-1" data-record-order="short" class="ajax">Click on me!</a>