简体   繁体   English

读取是否单击链接的Javascript代码

[英]Javascript code that reads if a link has been clicked

I have a simple bit of code (contained in a CMS and cant be edited) that and needs to be read by Javascript in the header if it has been clicked. 我有一些简单的代码(包含在CMS中,无法编辑),并且如果单击了该代码,则需要用标头中的Javascript读取。

Here is the code 这是代码

<div id="example" class="page-element-outer" style="text-align: left">
    <div class="page-element-inner" >
        <input type="image" name="Button1" id="Button" src="/getresource.axd?AssetID=16813" alt="Submit" style="text-align:left;" />
    </div>
</div>

Can you assist? 你能帮忙吗?

You can select the element through its ID and attach a click-event listener using the addEventListener method. 您可以通过其ID选择元素,并使用addEventListener方法附加单击事件侦听器。

document.getElementById("Button").addEventListener("click", callback, true);

function callback() {
   // Do some stuff in here when clicked
   alert("clicked");

   // Return false to prevent the browser default 
   // click-behaviour, if that is desired
   return false;
}

For legacy browsers 对于旧版浏览器

Older versions of IE doesn't support addEventListener , so for those you might need to do something like this: 较旧的IE版本不支持addEventListener ,因此对于那些版本的IE,您可能需要执行以下操作:

var el = document.getElementById("Button");
if (el.addEventListener) {
  el.addEventListener('click', callback, false); 
} else if (el.attachEvent)  {
  el.attachEvent('onclick', callback);
}

Wait for the DOM to be ready 等待DOM准备就绪

If you plan to run this in the head of your page, you'll need to wrap it a DOM-ready event listener as well, otherwise there is a change that the click event isn't attached to the element, as that element doesn't exist in the DOM when your script is run. 如果您打算在页面的头部运行此代码,则还需要将其包装为DOM就绪的事件侦听器,否则会发生更改,即click事件未附加到该元素,因为该元素不会运行脚本时,DOM中不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM