Most time I use a jQuery event handler to do CSS styling. And this is the first time I try to accomplish this by using the HTML event attribute. Here’s my code:
$('.navBtn').on('click', function() {
var length = $(this).closest('.videoList').find('.slider').length;
alert(`length A = ${length}`);
});
function btnClick() {
var length = $(this).closest('.videoList').find('.slider').length;
alert(`length B = ${length}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="videoList">
<div class="navBtn" onclick="btnClick()">Button</div>
<div class="slider">
<ul>
<li>items</li>
</ul>
</div>
</section>
The result of length A is 1 and length B is 0.
I think it’s probably that I mixed use jQuery with other stuff. But I want to know more details. Please explain to me or show me the information. Thanks!
2
Answers
You can pass
this
to the function:Then the function just accepts it as a parameter:
For example:
But this is kind of a step in the wrong direction. If you’re using jQuery, use jQuery. In lieu of jQuery, you can still attach the event handler in code:
Basically, try to avoid inline event handlers in general. Separate the markup from the code, and assign the event handlers in code.
You don’t need both an event attribute and a jQuery event, so just use the jQuery one. Event attributes like
onclick=
are discouraged. Also, you should use an<input type="range">
for sliders.