javascript - 将 $(this) 从一个函数传递到另一个函数

标签 javascript jquery

我在不同的类(class)有 2 个不同的事件:

$('.box1').click(function(){
$(this).find('something').css('red')
}

$('#otherId .box2').change(function(){
$(this).find('something').css('red')
}

但我打算把它们拆分成一个函数来避免重复代码

function getDetails(this){
  this.find(".something").css('red');
}

但是后面怎么调用这个函数呢?将 $(this) 传递给函数?

$('#otherId .box2').change(function(){
getDetails($(this))
}

最佳答案

this 是关键字,所以不能是参数名

function getDetails(el) {
    el.find(".something").css('red');
}

$('#otherId .box2').change(function () {
    getDetails($(this))
})

关于javascript - 将 $(this) 从一个函数传递到另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31331793/

相关文章:

javascript - 按跨度时删除 <li>

Javascript 函数返回数组未定义

php - 仅从 MySQl 中检索需要的信息或在 Jquery 中检索后对其进行过滤?

javascript - 使元素在jquery中失去焦点

javascript - 一些数据标签未显示在堆叠列 Highchart 中

javascript - 如何动态地将导航栏添加到 jQuery Mobile 应用程序

Javascript 如何拆分 JSON 数组,找到数字中的最大值,然后获取与其对应的名称?

javascript - 覆盖 Chrome 中的功能键默认操作

jquery - 使用 jquery append() 将按钮添加到表单

jquery - 移动菜单下拉菜单下推主要内容