首页 > 下面代码怎么优化

下面代码怎么优化

$(document).on("focus", ".footer input[type='text']", function() {
        this.value = "";
});
$(document).on("keypress", ".footer input[type='text']", function() {
        if (event.keyCode==13){
                
        }
});

感觉没什么可以优化的
要我的话就把document改成body 然后链式直接把两个on串起来
另外$("footer").val(); 这是什么鬼?

改完了更看不懂了
$(document).on("keypress", ".footer input[type='text']",func)
这种绑定写法一般是用于动态添加元素的 就是一个范围内可能先绑事件后有元素的
那么既然footer是不会动的直接$(".footer")或者给个id$("#footer")不是更好 难道还有好多footer不成
另外我不太懂input[type='text']的执行是先有[]选择器还是先执行input然后过滤[]
你的意思是footer里还有其他input么 如果是我直接给input上class 反正改样式也要用到


如果$('footer')不是动态创建的,没有必要使用事件代理,直接在它上面绑定事件好了。

另外如果一个jq对象会被重复使用,建议把它保存到一个变量里,因为$(...)是一个方法,是方法就需要执行时间,当平凡操作很多节点的时候就会感觉到卡了。当然几百个一般是感觉不出来的


说一点:

 ==改成===

$('.footer').find('.text').on({
    focus: function() {},
    keypress: function(event) {
        if (event.keyCode === 13) {
            console.log(event);
        }
    }
})

题主的event没有定义。
如果事件处理程序不是过多的话,不用使用事件委托。
input[type="text"] 一个类名 class="text"
$('.footer').find('.text')$('.footer input[type="text"]')效率高。
因为find()会调用浏览器的原生方法(getElementById,getElementByName,getElementByTagName等),所以效率比较高。而find(':text')没有原生方法,效率反而差一些。
参考以下代码,使用console.time()查看循环1000次消耗的时间。

console.time('.footer :text');
for (var i=0; i<1000; i++) {
    $('.footer :text');
}
console.timeEnd('.footer :text');

console.time('.footer .text');
for (var i=0; i<1000; i++) {
    $('.footer :text');
}
console.timeEnd('.footer .text');

console.time('.footer find :text');
for (var i=0; i<1000; i++) {
    $('.footer').find(':text');
}
console.timeEnd('.footer find :text');

console.time('.footer find .text');
for (var i=0; i<1000; i++) {
    $('.footer').find('.text');
}
console.timeEnd('.footer find .text');

【热门文章】
【热门文章】