[英]Anchor onclick should not reload the page but trigger javascript?
我有一种情况,我从c#动态添加一些内容到我的页面上的弹出框(这是一个div)
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();
}
如果我保持href =''on anchor它关闭窗口但重新加载页面,如果我删除它而不关闭窗口。
更改您的链接标记attr,如下所示,
//Edit changed from href="#" as it will scroll you to the top
href="javascript:void(0);" onclick='return action()'
并添加返回js函数,
function action() {
$('.myclass').hide();
return false;
}
添加return false;
在最后一行action()函数。 这将阻止默认链接操作 - 重新加载页面(在您的情况下,空href意味着“相同的URL”)。
加。 同时将onclick="action()"
更改为onclick="return action()"
。 或者onclick="action(); return false;"
。
使用<a href="#" ...
或<a href="javascript:void(0);" ...>
<a href="javascript:void(0);" ...>
。
我们已经知道<a href="#foo">Foo</a>
会创建一个指向同一页面中元素的链接,其ID为'foo'。 在这种情况下, #foo
称为片段标识符。 单击它将导致浏览器“跳转”到页面中的该元素而不重新加载它。
当片段标识符未提及页面中任何元素的ID时(例如<a href="#">Foo</a>
),浏览器将跳转到页面顶部。
function action() {
$('.myclass').hide();
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.