实例讲解jQuery实现html双向绑定功能
程序员文章站
2022-03-28 17:57:49
...
本文主要介绍了jQuery实现html双向绑定功能,涉及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="获取数据"></p> </body> </html>
相关推荐:
以上就是实例讲解jQuery实现html双向绑定功能的详细内容,更多请关注其它相关文章!