admin管理员组

文章数量:1406937

I'm trying to detect if certain element is clicked on onbeforeunload. I can't get it to work. Below is examples of the Javascript code and HTML code on the project (Please note that I have no control over the HTML element as it is not my site)

function checkLeave() {
   var p = document.getElementByElementById('yeah');
   if (p.href.onclick) {
      //do something
   }

   else {
      //do something else
   }
   }
 window.onbeforeunload = checkLeave;


 HTML CODE
 //The goSomewhere goes to another page
 <a id="yeah" href="javascript:goSomewhere();">
    <img src="smiley.png">
 </a>

Thanks in advance, J

I'm trying to detect if certain element is clicked on onbeforeunload. I can't get it to work. Below is examples of the Javascript code and HTML code on the project (Please note that I have no control over the HTML element as it is not my site)

function checkLeave() {
   var p = document.getElementByElementById('yeah');
   if (p.href.onclick) {
      //do something
   }

   else {
      //do something else
   }
   }
 window.onbeforeunload = checkLeave;


 HTML CODE
 //The goSomewhere goes to another page
 <a id="yeah" href="javascript:goSomewhere();">
    <img src="smiley.png">
 </a>

Thanks in advance, J

Share Improve this question asked Oct 4, 2011 at 2:24 jeezyfreezyjeezyfreezy 3021 gold badge4 silver badges13 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

What you need to do is bind an event handler to each <a href=""></a> on the page. This can be done with the following:

// Select all links
//var allLinks = document.querySelectorAll('a[href]');
var allLinks = document.links;

// Bind the event handler to each link individually
for (var i = 0, n = allLinks.length; i < n; i++) {
    //allLinks[i].addEventListener('click', function (event) {});
    allLinks[i].onclick = function () {
        // Do something            
    };
}

You are testing for the presence of the onclick property to the <a> tag. It isn't present in the markup. Rather than using the onclick, the markup calls a script as the element's href. So you need to look for a script in the href instead:

var p = document.getElementByElementById('yeah');
if (p.href.indexOf("javascript") === 0) {
   //do something
}
else {
   // do something else
}

Maybe something like this? (just the idea)

document.getElementById('yeah').onclick = function() {
  clicked = this.href;
};

本文标签: javascriptDetecting Href Is ClickedStack Overflow