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:
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.
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:
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.
$('outsideContainer ul li').click(function() {
//stuff
});
我没有包括实际上导致问题的javascript(它在//do stuff
,但是我遇到的问题是我正在寻找event.target只是outsideContainer而不是ul
和li
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.