今天在群里聊天,有个骚年提了一个问题,对w3cschool上的一个click时间的示例demo不解,我自己去看了下,发现也不懂,就是里面函数的参数问题,先贴代码。
<html>
<head>
<script src="//cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("div").click(function () {
$(this).css(
"width",
function (index, value) {
return parseFloat(value) * 1.2;
}
);
});
});
</script>
<style>
div {
width: 100px;
height: 50px;
background-color: red;
}
</style>
</head>
<body>
<div>请点击这里</div>
</body>
</html>
我的疑问是:这里的index
参数有什么作用?index
和value
的值是哪里来的?如果我去掉index
,后面的value
就会取不到值,为什么?
http://api.jquery.com/css/#css-propertyName-function
首先, function (index, value)
属于一个回调函数,是对选取的 div
的 width
修改取值的回调。
为什么有 index
? 因为这里 $("div")
选取的 div
可能会是多个的,那对每一个 div
都会单独执行这个回调函数,而区别这些 div
主要就通过 index
这个参数,其实就是一个识别序号。
为什么去掉 index
就不能正常取值 ? Js 里的回调函数比较智能,允许定义时省略后面的参数,但是不能省略前面的参数,如果你定义成 function (value)
,调用的时候也不会把 value
放到前面来,而是把原来 index
的值传给 value
。其实 index
和 value
这两个参数名无关紧要,名字可以随便定义,重要的是记住传递参数的实际意义,而这些是JQ手册里应该提供的。
1)首先问题click无关
2)这是个jQuery css方法调用问题
.css(prop,fun)
fun函数的参数为index,value
index为当前jQuerselector得到的集合索引值,value表示当前prop被修改前的值
func返回修改后的值,作为prop css属性的值
3)你去掉index,那么value不是取不到值,而是它的值为正确调用下的index值,而正确调用下的value被丢弃了
这两个参数是jquery给你的
它的css方法接受第二个参数作为回调
可以看下文档 http://api.jquery.com/css/#css-propertyName-function
你使用的是:.css( propertyName, function )
propertyName
Type: String
A CSS property name.
function
Type: Function( Integer index, String value ) => String or Number
A function returning the value to set. this is the current element. Receives the > > index position of the element in the set and the old value as arguments.
对于propertyName我们没有疑义,第二个参数是一个回调函数,它的返回值是你希望给那个元素设置的值,接受字符串或者数值作为返回结果,然后回调此函数时会传给你两个参数,第一个就是要设置的目标元素在你的选择器中的索引,第二个参数是那个目标元素的原有值