jQuery实现html双向绑定功能示例
程序员文章站
2022-03-21 20:32:54
本文实例讲述了jquery实现html双向绑定功能。分享给大家供大家参考,具体如下:
本文实例讲述了jquery实现html双向绑定功能。分享给大家供大家参考,具体如下:
<html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="jquery-1.9.1.js"></script> <script> var user = new user('123'); $(function(){ user.set( "name", "99" ); }); function getdata() { alert(user.attributes.name); } function databinder( object_id ) { var pubsub = jquery({}); var data_attr = "bind-" + object_id, message = object_id + ":change"; jquery( document ).on( "change", "[data-" + data_attr + "]", function( evt ) { var $input = jquery( this ); pubsub.trigger( message, [ $input.data( data_attr ), $input.val() ] ); }); pubsub.on( message, function( evt, prop_name, new_val ) { jquery( "[data-" + data_attr + "=" + prop_name + "]" ).each( function() { var $bound = jquery( this ); if ( $bound.is("input, textarea, select") ) { $bound.val( new_val ); } else { $bound.html( new_val ); } }); }); return pubsub; } function user( uid ) { var binder = new databinder( uid ), user = { attributes: {}, set: function( attr_name, val ) { this.attributes[ attr_name ] = val; binder.trigger( uid + ":change", [ attr_name, val, this ] ); }, get: function( attr_name ) { return this.attributes[ attr_name ]; }, _binder: binder }; binder.on( uid + ":change", function( evt, attr_name, new_val, initiator ) { if ( initiator !== user ) { user.set( attr_name, new_val ); } }); return user; } </script> </head> <body> <input type="text" data-bind-123="name" /><br/> <input type="button" onclick="getdata();" value="获取数据"></div> </body> </html>
更多关于jquery相关内容感兴趣的读者可查看本站专题:《jquery常见事件用法与技巧总结》、《jquery常用插件及用法总结》、《jquery操作json数据技巧汇总》、《jquery扩展技巧总结》、《jquery常见经典特效汇总》、《jquery动画与特效用法总结》及《jquery选择器用法总结》
希望本文所述对大家jquery程序设计有所帮助。