簡體   English   中英

無法從jquery'this'對象找到.attr

[英]Can't find .attr from jquery 'this' object

我正在嘗試從jquery中的html輸入查找數據屬性。 使用$(this).attr("data-jsonid"); 在下面的代碼中:

$.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () 
        {
            if(!isNaN(this.name))
            {
                var currentId = $(this).attr("data-jsonid");

                if (currentId !== undefined)
                {
                    alert(currentId);
                }
                if (o[this.name] !== undefined) 
                {
                    if (!o[this.name].push) 
                    {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } 
                else 
                {
                    o[this.name] = this.value || '';
                }
            }
        });
        return o;
    };
    $(function () {
        $('form').submit(function () {
            $('#result').text(JSON.stringify($('form').serializeObject()));
            return false;

我可以在html源代碼中看到,我所有的文本輸入都具有data-jsonid屬性,但是我無法確定javascript / jquery中的內容。 我只能在調試時找到名稱和值。

我創建了一個jsfiddle項目以幫助進行解釋, http://jsfiddle.net/mvargos/dSz38/ 如果單擊“提交查詢”,則會打印頁面的json。 我的最終目標是,我希望能夠讀取data-jsonid屬性,以便在該屬性存在的情況下格式化json的保存方式。 目前json已另存為

`{"1028":["Matt","Varg","27","2","Cris","Vargz","23","A"]}`

但是一旦我確定了data-jsonid,我想創建類似於以下內容的json:

`"1028":[{"id":"1", "tenantInfo":["Matt","Varg","27","2"]},{"id":"2", "tenantInfo":["Cris","Vargz","23","A"]}]`

我不確定我是在做一些錯誤的語法還是其他錯誤。 感謝您的幫助,如果這種解釋不正確,請告訴我。

var a = this.serializeArray();

上面的行序列化對象..

因此,基本上,您正在遍歷不是jquery對象array members

$.each(a, function ()   

$(this)在這種情況下不是適當的選擇器。

序列化之前,可以“記住”的jQuery的版本, this

$.fn.serializeObject = function() {

   var $this = $(this);

   ...

然后,當您要將$ this用作jQuery對象時,可以使用$ this。

   $this.data('some-data-attr');

this在這方面不是輸入元件,它只是一個普通的對象。 您必須導航回輸入以獲取該信息:

$("[name=" + this.name + "]").data("jsonid");

暫無
暫無

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

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