JS中的文本函数第一个参数(_)
Text function first param (_) in JS
<p class="myString">something to remove xxx here within a tag</p>
$('p.myString').text(function(_, txt) {
return txt.replace('xxx', '');
});
上面的代码有效,但第一个参数是做什么的? _
?
正如文档所述,第一个参数是您当前正在处理的元素的索引。
名为 _
的参数通常表示此参数将被忽略,并且不会在函数中使用。这只是一个约定,它仍然是一个有效的参数名称,没有什么可以阻止您使用此参数。
如果使用参数,参数的确切用途取决于框架 - 在这种情况下,jQuery文本函数如另一个答案中所述。
在你的代码段中,_
位于index
的位置,它位于.text(fn)
回调函数中的第一个参数,第二个是集合中的元素:
$('p.myString').text(function(_, txt) {
return txt.replace('xxx', _); // it changes all the "xxx" with their index values
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="myString">something to remove xxx here within a tag</p>
<p class="myString">something to remove xxx here within a tag</p>
<p class="myString">something to remove xxx here within a tag</p>
<p class="myString">something to remove xxx here within a tag</p>
<p class="myString">something to remove xxx here within a tag</p>
<p class="myString">something to remove xxx here within a tag</p>
<p class="myString">something to remove xxx here within a tag</p>
您可以看到_
表示元素的索引,因为_they相对于其parent_显示。
相关文章:
- 而循环只设置php中输入字段中的第一个值
- 错误:$injector:modulerr模块错误(我的第一个SPA应用程序)
- IE11中的第二个调用取消了第一个Fetch API调用
- Javascript XMLHttpRequest——只有第一个POST请求有效
- 使用javascript或angularjs特定过滤器搜索字符串中第一个img标记的json值
- 将OnClick函数设置为<ul>,最后一个ul是擦除第一个ul-s
- RxJS油门行为;立即获取第一个值
- Angular UI网格:如何通过第一个UI网格中的按钮使第二个UI网格可见
- 选择多个实例中的第一个
- 如何在调用下一个请求之前完成第一个Ajax Get请求
- 用javascript将参数从一个函数传递到另一个函数
- Lodash:返回对象的第一个键,该对象的值(即数组)中有一个给定的元素(即字符串)
- 看起来第一个console.log是'It’不太对
- 与杜兰达尔合作的第一个JavaScript项目.尝试从第三方 API 获取数据
- 节点发布错误对象的第一个“属性”
- 如果在第一个 jsp 页面设置了刷新参数,则会刷新所有 jsp 页面
- 使用 Function.prototype.bind.apply(Obj, args) 将参数传递给对象,只传递第一个元
- 提取第一个url参数,然后将其放入脚本标记中
- 第一个next()调用的参数所在的位置
- 逗号操作符返回参数列表中的第一个值,而不是第二个值