Javascript bind 与 jQuery bind
2015-07-28 09:08
561 查看
Javascript bind 与 jQuery bind
jQuery bind- bind() 方法为被选元素添加一个或多个事件处理程序,并规定事件发生时运行的函数。
- 规定向被选元素添加的一个或多个事件处理程序,以及当事件发生时运行的函数。
$("button").bind("click",function(){ $("p").slideToggle(); });
Javascript bind
– 对于给定函数,创建具有与原始函数相同的主体的绑定函数。 在绑定函数中,this 对象将解析为传入的对象。 绑定函数具有指定的初始参数。
– function.bind(thisArg[,arg1[,arg2[,argN]]])
– 下面的代码演示如何使用 bind 方法。
// Define the original function. var checkNumericRange = function (value) { if (typeof value !== 'number') return false; else return value >= this.minimum && value <= this.maximum; } // The range object will become the this value in the callback function. var range = { minimum: 10, maximum: 20 }; // Bind the checkNumericRange function. var boundCheckNumericRange = checkNumericRange.bind(range); // Use the new function to check whether 12 is in the numeric range. var result = boundCheckNumericRange (12); document.write(result); // Output: true
– 在下面的示例中,thisArg 对象与包含原始方法的对象不同。
// Create an object that contains the original function. var originalObject = { minimum: 50, maximum: 100, checkNumericRange: function (value) { if (typeof value !== 'number') return false; else return value >= this.minimum && value <= this.maximum; } } // Check whether 10 is in the numeric range. var result = originalObject.checkNumericRange(10); document.write(result + " "); // Output: false // The range object supplies the range for the bound function. var range = { minimum: 10, maximum: 20 }; // Create a new version of the checkNumericRange function that uses range. var boundObjectWithRange = originalObject.checkNumericRange.bind(range); // Check whether 10 is in the numeric range. var result = boundObjectWithRange(10); document.write(result); // Output: true
– 以下代码演示如何使用 arg1[,arg2[,argN]]] 参数。 绑定函数将 bind 方法中指定的参数用作第一个参数和第二个参数。 在调用绑定函数时指定的任何参数将用作第三个、第四个参数(依此类推)
// Define the original function with four parameters. var displayArgs = function (val1, val2, val3, val4) { document.write(val1 + " " + val2 + " " + val3 + " " + val4); } var emptyObject = {}; // Create a new function that uses the 12 and "a" parameters // as the first and second parameters. var displayArgs2 = displayArgs.bind(emptyObject, 12, "a"); // Call the new function. The "b" and "c" parameters are used // as the third and fourth parameters. displayArgs2("b", "c"); // Output: 12 a b c
相关文章推荐
- jQuery实现隔行变色
- jQuery基本选择器
- jQuery层次选择器
- 使用jQuery基本过滤选择器
- 基于jQuery鼠标滚轮滑动到页面节点部分
- 用onkeydown 判断输入的只为数字,和不能删除原有数据
- jQuery获取页面及个元素高度、宽度的总结――超实用
- JQuery实现鼠标滚轮滑动到页面节点
- 使用Browserify配合jQuery进行编程的超级指南
- 简单的jQuery入门指引
- 原创jQuery插件之loadmore
- jQuery整体架构
- 浅析jQuery核心架构中应用Closure(闭包)的设计模式
- jQuery 选取元素
- JQuery轮播图片效果
- 2015-07-23 JQuery第三课(JQuery元素:获取、添加、删除、设置、绑定、显示隐藏、回调函数、动画)
- jquery-mobile
- jquery学习成长记(一)
- JQuery选择器大全
- jquery 实现iframe 自适应高度