简体   繁体   中英

How do I modify this code so that the document searches for it every time?

How do I modify the following 3 lines of code so that they use $(document) ?

    $('.navbar li ul').slideToggle(300);

and

    $('.navbar > li:first-child > span').text("Category");

and

    if (!container.is(e.target)

example of usage of document:

    document.getElementById("input1").focus();

and

    $(document).on('click', '.navbar ul span', function(event) {    
    });

and

    $(document).mouseup(function (e) { 
    });

etc...

It appears you're a bit confused about jQuery selectors.

 $('.navbar li ul').slideToggle(300);

already searches the whole document. If you omit the second parameter to a jQuery object, it is implicitly the document . So, the selector above is equivalent to this:

 $('.navbar li ul', document).slideToggle(300);

Leaving out the document as the 2nd argument is a shortcut. If it is not present, it is assumed by default by the jQuery library.

Something like this:

document.getElementById("input1")

is a plain Javascript statement - no jQuery, no CSS selectors. It's another way to find an element by id and is roughly equivalent to the jQuery statement:

$("#input1")

or the plain Javascript:

document.querySelector("#input1");

From your comments, it appears that maybe what you're asking is how to use delegated event handling so that your queries will work with dynamically created elements. If that's the case, you should edit your question to actually say that. In the future, please describe the problem you are trying to solve, NOT your attempted solution. Then, we can help you more fully.

If that's the case, then you can use this, then delegated event handling only applies to event handlers, it does not apply to one time command like:

$('.navbar li ul').slideToggle(300);

That will work on whatever elements are present the moment you run it and there is no document equivalent or any way to make this work better or worse for dynamic elements. It works one whatever elements are present at the moment you call it because it's not an event handler installation for future events. It's an action you do at this particular moment so it can only work on the elements that are currently present.


You may find these other answers useful to learn more about these issues:

Should all jquery events be bound to $(document)?

jQuery .live() vs .on() method for adding a click event after loading dynamic html

JQuery Event Handlers - What's the "Best" method

Does jQuery.on() work for elements that are added after the event handler is created?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM