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

c# - Anchor onclick should not reload the page but trigger javascript? - Stack Overflow

programmeradmin3浏览0评论

I have a situation where I am dynamically adding some content to popup box (which is a div) on my page from c#

HtmlGenericControl content = new HtmlGenericControl();
content.InnerHtml = "<a id='close' href='' onclick='action()'>close</a><span>Some text here</span>";
divcontrl.Controls.Add(content);
divcontrl.Attributes.Add("class", "myclass");



javascript method:

function action() {
       $('.myclass').hide();
    }

If I keep href='' on anchor it's closing the window but reloading the page, if I remove it not closing the window.

I have a situation where I am dynamically adding some content to popup box (which is a div) on my page from c#

HtmlGenericControl content = new HtmlGenericControl();
content.InnerHtml = "<a id='close' href='' onclick='action()'>close</a><span>Some text here</span>";
divcontrl.Controls.Add(content);
divcontrl.Attributes.Add("class", "myclass");



javascript method:

function action() {
       $('.myclass').hide();
    }

If I keep href='' on anchor it's closing the window but reloading the page, if I remove it not closing the window.

Share Improve this question edited Feb 17, 2012 at 18:03 Jon Adams 25.2k18 gold badges84 silver badges121 bronze badges asked Jan 25, 2012 at 17:24 TigerTiger 4232 gold badges8 silver badges23 bronze badges 2
  • Try href='#', maybe that will help. – gdoron Commented Jan 25, 2012 at 17:27
  • Can you please show the rendered HTML? – gdoron Commented Jan 25, 2012 at 17:32
Add a ment  | 

4 Answers 4

Reset to default 4

Change your link tag attr as below,

//Edit changed from href="#" as it will scroll you to the top
href="javascript:void(0);" onclick='return action()' 

And add return to the js function,

function action() {
    $('.myclass').hide();
    return false;
}

Add return false; at the last line of action() function. This will prevent the default link action - reloading the page (in your case empty href means "the same URL").

Add. Also change onclick="action()" to onclick="return action()". Or onclick="action(); return false;".

function action() {
       $('.myclass').hide();
       return false;
    }

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

Use <a href="#" .... or <a href="javascript:void(0);" ...>.

We already know that <a href="#foo">Foo</a> would create a link to an element in the same page with ID as 'foo'. #foo in this case is called a fragment identifier. Clicking it would cause the browser to "jump" to that element in the page without reloading it.

When the fragment identifier doesn't mention the ID of any element in the page (e.g. <a href="#">Foo</a>), then the browser jumps to the top of the page.

发布评论

评论列表(0)

  1. 暂无评论