document.on('event')和$()。event之间的区别

时间:2015-06-09 17:34:34

标签: javascript jquery

我最近遇到了一个问题

public class MyAdapter extends ArrayAdapter<String> {
private Context context;
   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
       context = parent.getContext();
       context.getResources().getColor(R.color.red);
       return convertView;
   }
}

在某些情况下没有解雇,并在SO上找到了使用

的解决方案
$('.klass').change(function () { ... });

代替。解释是我的元素是在声明听众之后创建的,或者其他东西阻止了它被触发。

所以我应该永远不会使用第一种方法?并对任何事件使用第二种方法(点击,更改,...):

$(document).on('change', '.klass', function () { ... });

有人可以解释两者之间的区别和可能的陷阱。

3 个答案:

答案 0 :(得分:2)

change来电.on

$().change = function( types, data, fn ) {
    return this.on( types, null, data, fn );
}

答案 1 :(得分:2)

第一种方法很好,但正如您所说,您需要确保在创建事件处理程序之前已将元素加载到DOM中。

$(document).ready(function () {
   // dom has been loaded, now you can attach event handlers
})

正如@wZVanG所说的那样,change()只是呼唤on的糖,没有实际的区别。

答案 2 :(得分:1)

主要区别在于第二个允许使用多个事件。而不是说

$('.klass').click(function(){
    //some content
});
$('.klass').change(function(){
    //same exact content, repeated
});

你可以写

$('.klass').on('click change', function(){
    //some content, it applies to both now.
});

或者你可以使用(有点多余)

$(document).on('click change', '.klass', function(){
    //some content, it still applies to both.
});
相关问题