0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

jQuery attrを用いてカスタムdata属性を制御

Last updated at Posted at 2020-03-28
  • データ1
  • データ2

データ入れ替え

データ入れ替えボタンクリックでdata属性が入れ替えられます。


$(function(){
var $doc = 	$(document);
var PREFIX = {
TEST : 'test',
USER : 'user'
};
var $startElement = $('#startElement');
var $targetElement = $('#targetElement');

function getHtmlData($el, prefix) {
	var data = $el.attr('data-' + prefix),
		json = $.parseJSON(data),
		results = {};

	if (typeof json === "object") {
		$.each(json, function(k, v){
			results[k] = v;
		});
	} else if (data === 'string') {
		return data;
	}	
	return results;
}

function setHtmlData($el, data, prefix) {
	var type = typeof data;
	
	if (type === 'object') {
		$el.removeData('data-' + prefix); //cacheDataを削除
		$el.attr('data-' + prefix, JSON.stringify(data));
		
	} else if (type === 'string') {
		$el.removeData('data-' + prefix); //cacheDataを削除
		$el.attr('data-' + prefix, data);
	}	
	return $el;
}

function changeHtmlData($el, $el2, prefix) {
	var dataA = getHtmlData($el, prefix);
	var dataB = getHtmlData($el2, prefix);
	setHtmlData($el, dataB, prefix);
	setHtmlData($el2, dataA, prefix);
}

$doc.on('click','#changeData', function(e){
	changeHtmlData($startElement, $targetElement, PREFIX.USER);
});

});
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?