JSFiddle - React, Tailwind, and code Playground
HTML
<input type="button" value="新增" id="create_new" />
<div>測試</div>
CSS
div{
border:solid 1px #666;
padding:2px;
margin:0 0 5px 0;
width:80px;
text-align:center;
}
input{
width:80px;
padding:2px;
margin:0 0 5px 0;
}
JavaScript
// Utility
if ( typeof Object.create !== 'function' ) {
Object.create = function( obj ) {
function F() {};
F.prototype = obj;
return new F();
};
}
(function( $, window, document, undefined ) {
var Setting = {
init: function( options, elem ) {
var self = this;
self.elem = elem;
self.domStr = ( typeof options === 'string' )
? options
: options.domStr;
self.options = $.extend( {}, $.fn.appendWithSetting.options, options);
self.set();
},
set: function() {
var self = this;
$(self.domStr).appendTo(self.elem)
.data(self.options.attribute.name,self.options.attribute.value);
}
};
$.fn.appendWithSetting = function( options ) {
return this.each(function() {
var setting = Object.create( Setting );
setting.init( options, this );
});
};
$.fn.appendWithSetting.options = {
domStr: '',
attribute: {
name: 'counter',
value: 0
}
}
})( jQuery, window, document );
$(function(){
// 設定已存在的 DOM
$('div').each(function() {
$(this).data('counter', 0);
});
$('#create_new').click(function(){
// append DOM 時順便設定
$('body').appendWithSetting('<div>測試</div>');
//$('body').appendWithSetting({domStr: '<div>測試</div>', attribute: {name: 'hello', value: 1}});
});
$('body').on('click', 'div', function() {
var $this = $(this),
counter = $this.data('counter')+1;
$this.data('counter',counter)
.html('測試'+counter);
});
});