我正在尝试更新数据选项中的“id”和“selected”。
HTML:
<span class="re_highlight-feature" data-toggle="tooltip" data-animation="false" data-placement="top" title="" data-options="{'id':0,'name':'Appliance','value':'Dryer','selected':false}" data-original-title="Highlight Dryer">Dryer</span>
我能够引用它们并将正确的值传递给我的AJAX函数。
JS:
$('.re_highlight-feature').click(function(e) {
e.preventDefault();
var feature = $(this);
var featureDislay = feature.text();
var featureData = feature.data('options');
feature.html('<i class="fa fa-refresh fa-spin fa-fw"></i><span class="sr-only">Loading...</span>');
$.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: {action:'highlightFeature', id:featureData.id, name:featureData.name, value:featureData.value, selected:featureData.selected},
success:function(json){
obj = JSON && JSON.parse(json) || $.parseJSON(json);
var recordID = obj.id;
if (recordID == 0){
featureData['id'] = 0;
featureData['selected'] = false;
} else {
featureData['id'] = recordID;
featureData['selected'] = true;
}
feature.html(featureDislay);
feature.toggleClass('mark');
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
});
除此之外一切正常:
if (recordID == 0){
featureData['id'] = 0;
featureData['selected'] = false;
} else {
featureData['id'] = recordID;
featureData['selected'] = true;
}
我无法弄清楚如何在原始元素中更新这些值。
答案 0 :(得分:1)
请注意data-*
HTML
的属性应包含双引号括起来的属性,以便将data-*
属性值设置为JSON
{{1}内的有效HTML
}}
document
用于在
定义JavaScript对象的能力data-options='{"id":0,"name":"Appliance","value":"Dryer","selected":false}'
如果您要更新实际的var featureData = JSON.parse(feature[0].dataset.options);
,可以使用HTML
,HTMLElement.dataset
,JSON.stringify()
JSON.parse()
在if (recordID == 0) {
featureData.id = 0;
featureData.selected = false
feature[0].dataset.options = JSON.stringify(featureData);
} else {
featureData.id = recordID;
featureData.selected = true;
feature[0].dataset.options = JSON.stringify(featureData);
}
或.re_highlight-feature
检查DevTools
,表明Developer Tools
属性已在data-*
HTML
更新。
document
&#13;
var feature = document.querySelector(".re_highlight-feature");
var featureData = JSON.parse(feature.dataset.options);
console.log(featureData);
featureData.id = 1;
featureData.selected = true
feature.dataset.options = JSON.stringify(featureData);
console.log(JSON.parse(feature.dataset.options));
console.log(feature.outerHTML);
&#13;
答案 1 :(得分:0)
您的代码正在更新使用元素引用创建的数据对象。 对对象而不是实际元素进行更新。 要更新元素属性,请在featureData中设置值后使用以下代码。
feature.attr("data-options",JSON.stringify(featureData));