javascript - jquery click() event on <a> with id having certain prefix not firing the alert() function -


i'm trying set function listen when <a> tag has id value prefix , something. here's have:

$(document).ready(function() {        $("#mytable").datatable();      $('a[id |= "food"]').click(function() {      alert("a food link clicked!");      });       });
.some-class {    text-decoration: none;    color: black;   }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  <script src="https://cdn.datatables.net/1.10.10/js/jquery.datatables.min.js"></script>  <link type = "text/css" rel = "stylesheet" href = "https://cdn.datatables.net/1.10.10/css/jquery.datatables.min.css" />  <div>    <table id = "mytable">      <thead>        <tr>          <th>type</th>        </tr>      </thead>      <tbody>        <tr>          <td>            <a id = "food-1" class = "some-class" href = "#">bacon</a>          </td>        </tr>        <tr>          <td>            <a id = "food-2" class = "some-class" href = "#">pancakes</a>          </td>        </tr>        <tr>          <td>            <a id = "drink-1" class = "some-class" href = "#">beer</a>          </td>        </tr>      </tbody>    </table>  </div>

for reason, in snippet here, works expected. however, in browser (both firefox 43.0.3 , chrome 47.0.2526.111), there no response. know it's bad form ask question issue isn't reproducible, i'm hoping knows might preventing function running. there no errors , of other javascript/jquery functions run. reducing jquery function $("a").click(function()...) doesn't work. seems it's not recognizing fact link being clicked.

any appreciated.

update

i've been doing various things trying figure out why jquery isn't triggering alert when link clicked, seems jquery can't interact datatable @ all. following code had no effect on table.

$("#mytable").find("tr").css("background-color", "#000");

and following code produces object of length 0:

$("#mytable").children();

i'm @ total loss why jquery having such hard time interacting datatable.

cause

jquery datatables manipulates dom various reasons, therefore event handlers attached directly work first page only.

solution

you need use event delegation providing selector second argument in on() call, see example below:

$(document).ready(function() {     $("#mytable").datatable();     $('#mytable').on('click', 'a[id|="food"]', function(){       alert("a food link clicked!");    });  }); 

from jquery on() method documentation:

delegated events have advantage can process events descendant elements added document @ later time.

see "direct , delegated events" in jquery on() method documentation , jquery datatables – why click event handler not work more information.

see this jsfiddle code , demonstration.


Comments