最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to correctly set an URL calling a javascript function? - Stack Overflow

programmeradmin1浏览0评论

I am using jslint to check my javascript.

It's giving me repeatedly the following error:

Problem at line 236 character 18: Script URL.
a.href = "javascript:DoSomething(" + messageID + ");"

Probably, jslint is right. What would be the correct way to set the .href?

I am using jslint to check my javascript.

It's giving me repeatedly the following error:

Problem at line 236 character 18: Script URL.
a.href = "javascript:DoSomething(" + messageID + ");"

Probably, jslint is right. What would be the correct way to set the .href?

Share Improve this question asked Nov 1, 2010 at 19:19 newtogitnewtogit 5531 gold badge8 silver badges11 bronze badges 1
  • 2 Wow, the answers for this question are pletely pointless. #1 no one addressed your question. #2 people are giving you really bad advice. You should never use onclick. JS handlers should be binded at the JS layer, not inline with onclicks. – Eric Rowell Commented Jul 29, 2013 at 19:02
Add a ment  | 

6 Answers 6

Reset to default 4

Give it an onclick event handler instead, like this:

a.onclick = function() { DoSomething(messageID); };

Leave the href as # and either stop propgation or return false to stop the scroll, for example:

a.onclick = function() { DoSomething(messageID); return false; };

You should use the onclick event:

<a href="#" onclick="DoSomething(messageID);">Link Text</a>
<a href="#" onclick="javascript:DoSomething(" + messageID + "); return false;">Link</a>

I add the return false; to prevent the normal behavior of the a.

HREF should only be used for actual URLs. It is considered bad form to use "href="javascript:...".

An action calling JavaScript should go into the onclick attribute.

The mistake is that you're trying to set "click" behavior by changing the "href" in the first place. Don't do that. Instead, give the <a> tag a "click" handler, and set the "href" to "#" if you don't want the link to "go' anywhere.

to set: document.getElementById('myHref').href = "http://stackoverflow."

发布评论

评论列表(0)

  1. 暂无评论