简体   繁体   English

如何将onclick函数设置为多个元素?

[英]How to set onclick functions to multiple elements?

I am trying to use javascript to set the onclick property for my links. 我正在尝试使用javascript设置链接的onclick属性。 When the user clicks the link, I want to set a cookie. 当用户单击链接时,我要设置一个cookie。

Here is the code to set the cookie: 这是设置cookie的代码:

function setCookie(cookieName, cookieValue, cookiePath, cookieExpires){
    cookieValue = escape(cookieValue);
    if (cookieExpires == "") {
      var nowDate = new Date();
      nowDate.setMonth(nowDate.getMonth() + 6);
      cookieExpires = nowDate.toGMTString();
} if (cookiePath != "") {
  cookiePath = ";Path=" + cookiePath;
}
document.cookie = cookieName + "=" + cookieValue + 
  ";expires=" + cookieExpires + cookiePath;
}

function getCookieValue(cookieName)
{
var cookieValue = document.cookie;
var cookieStartsAt = cookieValue.indexOf(" " + cookieName + "=");
if (cookieStartsAt == -1)
{
  cookieStartsAt = cookieValue.indexOf(cookieName + "=");
}
if (cookieStartsAt == -1)
{
  cookieValue = null;
}
else
{
  cookieStartsAt = cookieValue.indexOf("=", cookieStartsAt) + 1;
  var cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt);
  if (cookieEndsAt == -1)
  {
     cookieEndsAt = cookieValue.length;
  }
  cookieValue = unescape(cookieValue.substring(cookieStartsAt,
     cookieEndsAt));
}
return cookieValue;
}

And now here is the code to set the onclick function: 现在,这里是设置onclick函数的代码:

var elements = document.getElementsByTagName('a');
   for(var i = 0, len = elements.length; i < len; i++) {
        elements[i].onclick = setCookie("workshop", elements[i].getAttribute("name"), "", "");
   }

I would like for the cookie value to be set as the name of the link. 我希望将cookie值设置为链接的名称。 For example, if I have a link <a href="#" name="test2"> , I want the cookie to be set to "test2". 例如,如果我具有链接<a href="#" name="test2"> ,则希望将cookie设置为“ test2”。

However, with this code, the cookie value keeps coming out to be the name attribute of the last < a > tag on the page (the last link). 但是,使用此代码,cookie值将继续成为页面上最后一个<a>标记(最后一个链接)的name属性。 I want each link to have their own onclick function; 我希望每个链接都具有自己的onclick函数; not all of them to set the cookie to the same value. 并非所有人都将Cookie设置为相同的值。 This way, once the user reaches the next screen, I will know which link they clicked to get there. 这样,一旦用户到达下一个屏幕,我就会知道他们单击了哪个链接到达那里。

ANY HELP IS GREATLY APPRECIATED! 任何帮助是极大的赞赏! THANKS AHEAD! 谢谢!

Use the addEventListener() function instead of an onclick event handler. 使用addEventListener()函数代替onclick事件处理程序。 Something like this should do what you want: 像这样的事情应该做你想要的:

var elements = document.getElementsByTagName('a');
for (var i = 0, len = elements.length; i < len; i++) {
  elements[i].addEventListener("click", function() {
    setCookie("workshop", this.getAttribute("name"), "", "");
  });
}

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

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