理解并使用这个'在jQuery函数中

时间:2016-09-06 19:28:26

标签: jquery this

我有一个函数,我想应用于不同的元素 - 或者更确切地说,不同的选择器创建不同的上下文。如何修改以下函数以使用this,而不是在getClass函数中指定$('#themes')选择器?

代码:

$('#themes').change(function(e) {
  getClass(this, e); 
});

function getClass() {
  var classToAdd = $('#themes').find('option[value]:selected').map(function() {
    return this.value;
  }).get().join(' ');
  var allClassess = $('#themes').find('option[value]').map(function() {
    return this.value ? this.value : null;
  }).get().join(' ');
  $('#result').removeClass(allClassess).addClass(classToAdd);
}

请参阅fiddle here

4 个答案:

答案 0 :(得分:1)

该事件具有currentTarget属性,这正是您正在寻找的属性,无需将this传递给它......事实上,只需重新配置绑定:

$('#themes').on('change', getClass);

function getClass (event) {
  var themes = $(event.currentTarget);
  var classToAdd = themes.find('option[value]:selected').map(function() {
    return this.value;
  }).get().join(' ');

  var allClassess = themes.find('option[value]').map(function() {
    return this.value ? this.value : null;
  }).get().join(' ');

  $('#result').removeClass(allClassess).addClass(classToAdd);
}

答案 1 :(得分:1)

'this'运算符与作用域有关,以及您正在处理的当前对象是什么。如果当前没有选择任何对象,那么'this'将引用'document',也称为整个网页。您可以为传递的选择器分配一个新变量,这是完成您正在做的事情的一种相当简单的方法:

('#themes').change(function(event) {
  getClass(this, event);
});

function getClass(elem, e) { //if you pass args into a func, you need to declare them in the prototype
  //elem now represents whatever object you passed it (in this case 'this')
  var classToAdd = elem.find('option[value]:selected').map(function() {
    return this.value;
  }).get().join(' ');
  var allClassess = elem.find('option[value]').map(function() {
    return this.value ? this.value : null;
  }).get().join(' ');
  $('#result').removeClass(allClassess).addClass(classToAdd);
}

另一个选择是使用方法或jQuery插件,但是这个语法比这个函数更需要解决。在使用方法和插件前进之前,了解此函数如何将对象作为变量。

我希望这有帮助!

答案 2 :(得分:0)

使用$(this)代替this
这样你就不必定义相同的jQuery选择器。

答案 3 :(得分:0)

了解$(this)this

之间的区别非常重要

$(this) - 是一个包含this的jQuery对象,所以只要你想运行任何jQuery函数就可以使用$(this)

this - 是一个Javascript对象,因此您要使用的任何Javascript函数都应该在this上使用。

此外,使用this时,它取决于函数的调用方式。您不需要将thise传递给getClass函数。一个简单的$('#themes').change(getClass);将在#themes更改时执行该功能,this函数中的getClass关键字将是#themes$(this)的选择对象1}}将是包含this

的jQuery对象

相反,你可以使用$(this).find(':selected')而你应该做得好。不过请注意,this函数中的map关键字是指您正在运行map函数的对象(又名$(this).find(':selected')

相关问题