简体   繁体   中英

How do you select multiple elements for a javascript click event to be captured on?

I have this HTML:

<div id="outsideContainer">
<ul>
<li>Hello</li>
<li>Goodbye</li>
</ul>
</div>

With jQuery how would I say when any of those elements is clicked execute a certain function?

I had this but it did not work:

$('#outsideContainer').click(function() {
//do stuff
});

Any ideas?

For the most part that's fine. Possible reasons it wouldn't work:

  1. You're executing your JavaScript before the "outsideContainer" element exists, eg:

     ... <script> $('#outsideContainer').click(function() { //do stuff }); </script> <div id="outsideContainer"> <ul> <li>Hello</li> <li>Goodbye</li> </ul> </div> 

    The element must exist as of when the script is called. Either just put your script block at the very end of the page, just before the closing body tag, or wrap your code in a function you pass into jQuery's ready function.

  2. You're expecting this within your callback to refer to the li element; in fact, it will refer to the "outsideContainer" div , because that's what the event handler is hooked to. You can get at the li element via event.target :

     $('#outsideContainer').click(function() { // here, this is the raw "outsideContainer" element // and event.target is the raw element that was clicked }); 

    Note that depending on your margins and padding, event.target might be the ul element, if you click within the ul but not on a li .

Other things that may be worth looking at:

  • delegate - Hook an event on a container but have jQuery filter the events you get depending on what child was clicked.
  • live - Basically document-wide delegate .

This will only fire when you click on the entire div.

$('#outsideContainer').click(function() {
    //do stuff
});

To capture a click on each individual li do:

$('#outsideContainer ul li').click(function() {
    //do stuff
});

As noted by TJ Crowder, what you have works, but you will want to be aware of the context of this . Substituting event.target for this will give you the actual element that was clicked.

As a demonstration, I have included below a fiddle that will alert the node (tag) type and text content of the clicked element. The <div> , <ul> , and <li> s all have different colored borders to help you visually determine what you are actually clicking on.

Live demo ->

$('outsideContainer ul li').click(function() {
//stuff
});

我没有包括实际上导致问题的javascript(它在//do stuff ,但是我遇到的问题是我正在寻找event.target只是outsideContainer而不是ulli s。

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