-1

I need JS onclick event but it works very strange for me and I can't figure out why. There're three examples below and I don't understand why the first one doesn't.

/ First

$(document).ready(function () {

$("button#clear-id").click(function(){      // this one doesn't work
    alert('Howdy');
});
...

/ Second

$(document).ready(function () {

$("body").click(function(){      // this one works
    alert('Howdy');
});
...

/ Third

$(document).ready(function () {

$(document).on('click', '#clear-id', function () {    // this one works
  alert("Hello!");
});
...

/ HTML of the button looks like

<button type="button" class="close" id="clear-id" aria-label="Close" value="';   the_ID(); echo'">
    <span aria-hidden="true">&times;</span>
</button>
Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
  • Possible duplicate of [What is DOM Event delegation?](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) – Zenoo Jul 29 '18 at 10:29
  • [Can't reproduce.](http://jsfiddle.net/591ku2z8/) – Ivar Jul 29 '18 at 10:40
  • I can see some similarities but I think my question is different. Why $("#clear-id").click(function(){ doesn't work ? The selector works but the function doesn't. – Deyan Veselinov Jul 29 '18 at 10:46
  • Ivar I already tested this on jsfiddle even for multiple buttons to get their values but on my local.wp it wants $(document) to work – Deyan Veselinov Jul 29 '18 at 10:51

1 Answers1

-1

Evidently the selector in the first one is wrong, use only $('#clear-id') instead, because I'm not sure but I think you can't combine tag with id in the same selector.

vitomadio
  • 1,034
  • 5
  • 14