简体   繁体   English

访问JQuery data-json元素

[英]Accessing JQuery data-json elements

I have the followings anchors on the page: 我在页面上有以下锚点:

<a href="#" data-json='{"first":"SGVsbG8=","last":"V29ybGQ=","mail":"aGVsbG9Ad29ybGQuY29t","favorite":"eWVz","answer":"VGhpcyBpcyBteSBhbnN3ZXJzIQ==","id":"MQ==","read":"yes"}'>Hello</a>

<a href="#" data-json='{"first":"SGVsbG8=","last":"V29ybGQ=","mail":"aGVsbG9Ad29ybGQuY29t","favorite":"eWVz","answer":"VGhpcyBpcyBteSBhbnN3ZXJzIQ==","id":"MQ==","read":"no"}'>Hello</a>

What I want is to change data-json read value to no for anchors whose first value is SGVsbG8= 我想要的是将first值为SGVsbG8=锚点的data-json read值更改为no

I tried following but didn't work: 我试过以下但没有奏效:

($('.usr-list a').data('json').first == 'SGVsbG8=').each(function(i){$(this).data('json').read('no')});

Is that possible to do? 这可能吗?

Yes, this is possible. 是的,这是可能的。 Result of a comparison ($('.usr-list a').data('json').first == 'SGVsbG8=') is a boolean value which doesn't have each method, for filtering the elements you should iterate through them and read their data-json attributes: 比较结果($('.usr-list a').data('json').first == 'SGVsbG8=')是一个布尔值,没有each方法,用于过滤你应该迭代的元素通过它们并读取他们的data-json属性:

$('a').each(function () {
    var o = $(this).data('json');
    if (o.first === 'SGVsbG8=') {
        o.read = 'no';
    }
});

Please note that the above snippet doesn't change the data-json attributes. 请注意,上面的代码段不会更改data-json属性。 jQuery data method after parsing the data-* atributes stores them internally. 解析data后的jQuery data方法 - data-* atributes在内部存储它们。 If you want to change the attributes after modifying the property you should JSON encode the objects and reset the attributes. 如果要在修改属性后更改属性,则应对JSON进行编码并重置属性。

this.setAttribute('data-json', JSON.stringify(o));
function updateJson(object) {
$("a").each(function() {
   var json = $(this).data("json");
   if(json["first"]==object["first"]) {
     json["read"] = "no";
     $(this).data("json",json);
   }
});
}

updateJson({first : "SGVsbG8="});

This can be used for that purpose :) 这可以用于这个目的:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM