简体   繁体   English

我可以像 onclick 一样使用 href 吗?

[英]Can I use href like an onclick?

I just can not figure a way to use location.href to act like you're clicking on a link.我只是想不出一种方法来使用 location.href 来表现得好像你在点击一个链接。 What I am trying to do is get the variables included, for example,我想要做的是获取包含的变量,例如,

The regular link is like this and works fine:常规链接是这样的,工作正常:

<a href="images/someImage.jpg" title="My Image" rel="gb_page_center[249, 266]">Click Me</a>

I am trying to call a function using href (or some other method) to open the image with the other parameters just as if you were to click on the link.我正在尝试使用 href(或其他一些方法)调用一个函数来使用其他参数打开图像,就像您要单击链接一样。

I hope I am explaining this correctly.我希望我能正确解释这一点。

Thanks for any help.谢谢你的帮助。

-UPDATE- -更新-

I finally found my solution here Displaying the Popup box generated by Greybox on page load(onLoad)我终于在这里找到了我的解决方案在页面加载时显示由 Greybox 生成的弹出框(onLoad)

Thank you all for your suggestions.谢谢大家的建议。

回答:是的。

<a href="javascript:yourFunction(); return false;" title="My Image" rel="gb_page_center[249, 266]">Click Me</a>

Add an onclick event to your link.将 onclick 事件添加到您的链接。 Using JQuery, you could ofcourse bind the click event to the links, and use .preventDefault() to block the anchor tag workin.使用 JQuery,您当然可以将点击事件绑定到链接,并使用 .preventDefault() 来阻止锚标记工作。 Much cleaner code also.更干净的代码。

$(document).ready(function(){
  $('a').bind('click', function(e){
    e.preventDefault();
    //do whatever you wish to do
  });
});
<a onclick="yourJSFunction();return false" href="images/someImage.jpg" title="My Image" rel="gb_page_center[249, 266]">Click Me</a>

You just need to add an onclick attribute to your anchor tag.您只需要为您的锚标记添加一个onclick属性。
Make sure to return false or else the anchor tag will go to the URL like normal.确保返回false否则锚标记将像往常一样转到 URL。

location.href or window.location.href refers to the browsers current address. location.hrefwindow.location.href指的是浏览器的当前地址。 If you change the value of location.href the browser will use that value as it's address.如果您更改location.href的值,浏览器将使用该值作为地址。 So if you want to navigate your browser to a link programmatically, you just have to change its value.因此,如果您想以编程方式将浏览器导航到链接,则只需更改其值。

If you just want a clickhandler for your link don't use onclick or href, that's just bad practice, use a sepperate script that does this unobtrusively like so:如果您只想要链接的点击处理程序,请不要使用 onclick 或 href,这只是不好的做法,请使用单独的脚本,该脚本不显眼地执行此操作,如下所示:

var button = document.getElementById('button');
button.onclick = function(){
     do_something();
}

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

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