1

In this code have button and anchor with click event.

alert(document.getElementById("btn").click); //not working in safari
alert(document.getElementById("btn1").click); // is working in safari

I want to execute anchor's click event What I do?

<head>
<script type="text/javascript">
function clickMe()
{
     alert('My Name is ' + event.srcElement.name);
}
</script>
</head>
<body>
<a href="#" name="btn" id="btn" onclick="clickMe()">a</a>
<input type="button" href="#" name="btn1" id="btn1" onclick="clickMe()" />
<script>

//document.getElementById("btn").click();
alert(document.getElementById("btn").click);
alert(document.getElementById("btn1").click);
</script>
</body>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user380790
  • 29
  • 1
  • 4

2 Answers2

1

Try this way

    <!DOCTYPE html>
    <html>
      <head></head>
      <body>
        <a href="#" name="btn" id="btn">a</a>
        <input type="button" href="#" name="btn1" id="btn1"  />
        <script>
          function teste(){
             alert('You clicked on an anchor');
          }

          window.onload = function() {
            document.querySelector("#btn").addEventListener("click", teste);
          };
        </script>
      </body>
    </html>
0

Taken from another question Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

I did some research and it seems that the .click is not suppose to work with 'a' tags because the browser does not suport "fake clicking" with javascript. I mean, you can't "click" an element with javascript. With 'a' tags you can trigger its onClick event but the link won't change colors (to the visited link color, the default is purple in most browsers). So it wouldn't make sense to make the $().click event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser.

Safari and Chrome will not allow the link object to have a .click function, because of this behavior. It would appear that IE is less strict.

Community
  • 1
  • 1
Jack B Nimble
  • 5,039
  • 4
  • 40
  • 62