سؤال

I have the following code that is part of a dynamic loop and creates a new grid with 1 column and 4 rows. The forth row has a button:

var elem = $(this,'a[data-itemid]');
$(elem).prop('data-itemid', '"'+value+'"');
console.log($(elem).prop('data-itemid'));
console.log(elem);

Using developer console, here is how the is drawn:

<a data-role="button" name="orderButton" dsid="orderButton" class="menuMaster_orderButton    ui-link ui-btn ui-btn-b ui-icon-none ui-btn-icon-nowhere ui-shadow ui-corner-all" id="menuMaster_orderButton" data-corners="true" data-icon="none" data-iconpos="nowhere" data-mini="false" data-theme="b" tabindex="7" role="button">Order!</a>

As it cycles through each record, I have the above code which should add a new attribute called 'data-itemid' and a value. On this line:

console.log($(elem).prop('data-itemid'));

It gives me the correct value. So I know it's adding the new attribute. But I do not think its adding it to because i cannot find it at all.

console.log(elem);

This gives me :

[Window, jquery: "1.9.1", constructor: function, init: function, selector: "", size: function…]

Which is not the element :(

UPDATE:

This what i am using during the loop as the buttons being created:

$(this,'a[name=orderButton]').data('itemid', value);

This is what is used to fetch it onClick:

console.log('itemid= '+$(this, 'a[name=orderButton]').data('itemid'));

The above comes back undefined.

هل كانت مفيدة؟

المحلول

jQuery stores all data attributes in an object in memory to improve performance. Any attributes added to an element after the DOM has loaded is stored in this object only, and will not visible in the HTML source.

You can verify a data attribute has been set by using data() to retrieve it. Do not use prop('data-x') or attr('data-x'); as it the attributes are not guaranteed to exist for the above reason, and it's much slower.

With this in mind your first example should be:

var elem = $(this,'a[data-itemid]');
$(elem).data('itemid', value);
console.log($(elem).data('itemid'));
console.log(elem);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top