Should I Be Using $(document)

2019-09-19 03:42发布

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.

The code was like this:

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

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

I now use the following instead:

$(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?

标签: jquery
1条回答
干净又极端
2楼-- · 2019-09-19 03:49

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

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

As for the original question:

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.

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.

查看更多
登录 后发表回答