using .closest with .click
I'm attempting to use .closest to grab the closest <li>
value based on clicking one of the <li>
elements. I'm not having much luck开发者_开发百科. First off, I'm not having much luck trying to figure out how to add the .click
part to the .closest
.
Thanks in advance.
<script>
$(document).ready(function() {
var test = $('#test').closest('li').text();
alert(test);
});
</script>
</head>
<body>
<tbody>
<ul id="test">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
To hook up the onclick event you use the click
method and provide a function as event handler:
$('li').click(function() { ... });
In the event handler you can use this
to access the element that was clicked on:
var test = $(this).text();
As you are getting the text inside the element, you don't want to use the closest
method as that is used to find a different element (specifically a decendant element).
So:
$(function() {
$('li').click(function() {
var test = $(this).text();
alert(test);
});
});
精彩评论