0

Im trying something simple, i am quite noob in jquery and i don´t know how to make an click event when you click in an a tag that is inside a span tag, this is my code.

<span>
    <a class="paginate_button current" aria-controls="table_id" data-dt-idx="1" tabindex="0">1</a>
    <a class="paginate_button " aria-controls="table_id" data-dt-idx="2" tabindex="0">2</a>
    <a class="paginate_button " aria-controls="table_id" data-dt-idx="3" tabindex="0">3</a>
    <a class="paginate_button " aria-controls="table_id" data-dt-idx="4" tabindex="0">4</a>
</span>

I tried this but it doesn't work

$("#table_id_paginate > span > a.paginate_button").click(function() {
alert("Handler for .click() called.");});
DeathInWhite
  • 117
  • 1
  • 10
  • 5
    `$(".paginate_button").click(...)`? Unless you need to worry about scope, just targeting the class `paginate_button` should be fine, right? – Tim Lewis Sep 25 '19 at 20:27
  • 1
    Are you getting any error messages in your console? Do you have the jquery linked to your page? – Jermaine Subia Sep 25 '19 at 20:28
  • 1
    Potentially relevant: [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – VLAZ Sep 25 '19 at 20:29
  • 3
    is the span a child of `#table_id_paginate` or a descendant? if it's a decendant rather than a direct child then use `"#table_id_paginate span > a.paginate_button"` – Jaromanda X Sep 25 '19 at 20:29

3 Answers3

2

The markup you provided does not have an element with the ID "table_id_paginate". So jQuery is selecting the links because it is looking for a elements with the class paginate_button who are direct descendants of a span that is a direct descendant of an element with that ID.

So if you change your code to how Tim Lewis commented: $(".paginate_button").click(...) the code works.

Tanner
  • 1,695
  • 9
  • 18
0

Just making this change will make it work, basically you want that any <a> tag with .paginate_button class should work on click.

<script>
$("span > a.paginate_button").click(function() {
alert("Handler for .click() called.");});
</script>

Edit : How to go about these : Figure out the target element, then keep going up towards the parent and that becomes your target.

vS12
  • 300
  • 2
  • 8
-1
$("a.paginate_button").on("click", function () {
     //your code here
})
  • 3
    The provided answer was flagged for review as a Low Quality Post. Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). This provided answer may be correct, but it could benefit from an explanation. Code only answers are not considered "good" answers. From [review](https://stackoverflow.com/review). – MyNameIsCaleb Sep 26 '19 at 01:51