从同一IP地址点击第三个链接调用JS函数

Call JS function on 3rd href link clicked from the same IP address

本文关键字:三个 链接 调用 函数 JS IP 地址      更新时间:2023-09-26

我有几个。html页面,每个页面都有一些href链接。
请帮助我的代码调用JS函数在第三次点击从相同的IP上的任何链接。

例子:
IP 111.111.111.111第一次点击链接什么都不做
IP 111.111.111.111第二次点击链接不做任何事
IP 111.111.111.111第三次点击链接onclick="call_function();"

要获得IP,我将使用此答案中的代码https://stackoverflow.com/a/2031935/4805488

像下面这样…

另外,如果你需要这种情况持续一段时间和切换页面等,你需要添加一个唯一的id到每个链接,然后将其存储在cookie或服务器端,根据它是多么重要,正好3个点击每个链接。

将"data-clicked"添加到链接中,您可以添加其他链接,这些链接不会以相同的方式起作用。

window.addEventListener('click', function(e) {
  
    if (e.target.getAttribute("data-clicked") == undefined) { return true; };
    
    var clk = parseInt(e.target.getAttribute("data-clicked"));
  
    if (clk >= 2) {
      e.target.setAttribute('data-clicked', 0);
      
      alert("Clicked 3 times");
      
    } else {
      e.target.setAttribute('data-clicked', clk + 1);
      
    }
  
    e.preventDefault();
  
    return false;
  
});
<a href='http://stackoverflow.com/' data-clicked='0'> Click me 3 times </a>

<a onclick="call_function(this, alertMe);">click me</a>

你可以这样做:

function call_function(element, callback) {
   //check to see if clicked before or else start with 0;
   var clicked = parseInt(element.getAttribute('data-clicked') || 0);
   // increment the amount of clicks
   clicked++;
   // store the click amount in a data attribute
   element.setAttribute('data-clicked', clicked);
   // return the callback when the click amount 3 or greater. 
   return clicked >= 3 ? callback() : false;
}
function alertMe() {
   alert('wow! 3 times is....')
}

如果你想让点击的数字持续一段时间(直到localStorage再次被清除),你也可以使用localStorage. setitem()和localStore.getItem()来代替setAttribute和getAttribute

实现这一目标的一些想法:

  • 使用本地存储为每次访问增加一个值(这里是我为您的情况编写的一个示例,在3次单击后显示警报:http://jsbin.com/mamebeyiye/edit?html,js,output)
  • 将此信息存储在cookie中
  • 你也可以在服务器端管理这个,但这是另一个故事,可能更困难

这个链接可以帮助您决定在cookie和本地存储之间哪个解决方案是最好的。