簡體   English   中英

jQuery設置attr,然后獲取attr

[英]jQuery Set attr and then Get attr

我正在創建一個設置2個屬性的頁面,然后我試圖在頁面加載后引用這些屬性。

我已經能夠毫無問題地設置屬性,如果我將它們硬編碼到信用和借記屬性中,我也能夠引用這些屬性。

但試圖動態調用它們是行不通的。 接受建議。

<div class="net" credit="" debit=""></div>


$(document).ready(function() {
    ... some fancy code involving arrays and junk ...
    if(TYPE == 'credit') {
        $(".net").attr('credit',data.response.stats.total);
    } else if (TYPE = 'debit') {
       $(".net").attr('debit',data.response.stats.total);
    }
});

$(window).bind("load", function() {
    afterPageLoad();
});

function afterPageLoad(){
    total_credit = $(".net").attr('credit');
    total_debit = $(".net").attr('debit');
    total = (total_credit - total_debit);
    $(".net").html( "$"+total );
}

建議使用jQuery.data()可以讀取的data-屬性

<div id="test" data-foo="bar"></div>

得到

alert( $('#test').data('foo'))

$('#test').data('foo','new value, or object or array'))

不必存在使用此屬性的屬性。 您可以隨時在元素上存儲任何內容,也可以在標記中讀取數據。

jQuery.data()API文檔

問題是“......一些涉及數組和垃圾的奇特代碼......”

data.response表明您正在進行異步的Ajax調用,並且您嘗試在設置之前讀取屬性。

將邏輯放在Ajax調用的回調中,不要在onload部分調用。

要讀取動態屬性值,需要使用prop()而不是attr()

理想情況下,您應該將自定義值存儲在data-屬性(即data-credit )中,然后使用jQuery的data()方法來獲取/設置值。

當抓取total_credittotal_debit的屬性時,你應該使用parseFloat();

例如: parseFloat( $(".net").attr('credit') );

您還應該在未設置屬性的情況下設置回退。

例如: total_credit = parseFloat($(".net").attr('credit')) || 0; total_credit = parseFloat($(".net").attr('credit')) || 0;

$(document).ready(function() {
    var TYPE = 'credit';
    if(TYPE == 'credit') {
        $(".net").attr('credit', 123);
    } else if (TYPE = 'debit') {
       $(".net").attr('debit', 53);
    }
});

$(window).bind("load", function() {
    afterPageLoad();
});

function afterPageLoad(){
    total_credit = parseFloat($(".net").attr('credit'))||0;
    total_debit = parseFloat($(".net").attr('debit'))||0;
    total = (total_credit - total_debit);
    $(".net").html( "$"+total );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM