我应该使用$(document) [英] Should I Be Using $(document)

查看:66
本文介绍了我应该使用$(document)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Web应用程序中,我有一个购物车,该购物车具有AJAX删除/删除按钮,该按钮刷新购物车并显示新的购物车.

In my web application I have a shopping cart that has an AJAX remove/delete button, which refreshes the cart and shows the new cart.

代码如下:

$(".delBtn").on("click", function(){
    // Code here
});

会发生什么事,当显示新购物车时,删除按钮将不再起作用.

What would happen is when the new cart was displayed the delete button would no longer work.

我现在改用以下内容:

$(document).on("click", ".delBtn", function(){    
    // Code here
});

它可以按预期工作,但是它是最好的选择吗?高级开发人员或专家会认为这是错误的代码吗?

It works as expected, but is it the best option available? Would a senior developer or an expert think that it's bad code?

推荐答案

首先,为什么第一个代码段不起作用.

First, why the first code snippet doesn't work.

第一个代码所说的是选择当前页面上的每个元素 ,其类别为" delBtn",并在单击该元素时运行一个函数."但是,在您执行此操作时,您的按钮不在页面上(因为尚未添加),因此将找不到任何元素.相比之下,第二种方法说,每当您单击页面时,如果被单击的元素都具有"delBtn"类,则运行该函数.因为这只是寻找网页上的点击,所以它适用于以后添加的元素

What the first code says is "select every element currently on the page with a class of "delBtn", and, when that is clicked, run a function." However, at the time you do that, your button isn't on the page (since it hasn't been added yet), so no elements will be found. In comparison, the second method says that whenever you click the page, if the clicked element has the class "delBtn", then run the function. Because this just looks for clicks on the webpage, it will work for elements that are added later

关于原始问题:

是,不是.可以,但是您可能需要将其更改为其他内容.这种工作方式是jquery侦听文档上的每个click事件,并检查clicked元素是否与选择器匹配.因此,每次您单击页面上的内容时,jquery都必须运行一些代码.

Yes and no. It is okay, but you might want to change this to something different. The way this works is that jquery listens to every click event on the document, and checks to see if the clicked element matches the selector. Because of this, jquery must run some code every time you click something on the page.

您可能应该做的是将$(document)更改为包含该按钮的任何父元素.这将具有更好的性能,因为jquery只需检查包含按钮的实际元素上的click事件.

What you probably should do instead is change $(document) to whatever parent element contains the button. This will have better performance since jquery only has to check click events on the actual element that contains the button.

这篇关于我应该使用$(document)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆