[英]how to call a javascript function if the href has the hash tag id
如果href具有哈希标签ID,我想在href上调用javacsript函数。我需要#table,因为我正在使用引导程序选项卡,因此无法使用javasript:show_create_msg(); 这是我的代码
<a href="#table:show_create_msg();">Table</a>
function show_create_msg()
{
alert("error");
}
添加
onclick
事件并prevent
click事件,那么当您单击链接时,它不会加载页面。
<a href="#table" onclick="show_create_msg();">Table</a>
<script>
function show_create_msg()
{
alert('is working');
// Do something;
return false;
}
</script>
如果您需要找到哈希
http://example.com#table
<script>
function show_create_msg()
{
alert('is working');
// Do something;
return false;
}
var hash = window.location.hash;
if(hash == '#table'){
show_create_msg();
}
<script>
将onclick
事件添加到此链接,然后编写一个执行以下操作的JavaScript函数:
<a href="#" onclick="show_create_msg();">Table</a>
<script>
function show_create_msg()
{
// Do something;
}
</script>
您可以为您的元素指定一个ID,并为其添加click事件。
我将向您展示如何以更适当的方式进行操作(内联使用“ onclick”元素不是一个好习惯)
这是一个例子:
HTML
<a id="myLink" href="#table">Table</a>
jQuery的
$('#myLink').on('click',function(){
show_create_msg();
});
甚至更好:
$('#myLink').on('click',function(){
// your show_create_msg code here
});
如果要防止默认链接行为:
$('#myLink').on('click',function(e){
e.preventDefault();
// your show_create_msg code here
});
如果只想在特定的哈希值上触发代码:
$('#myLink').on('click',function(e){
var hash = window.location.hash;
if(hash=='#table'){
// your show_create_msg code here
}
});
如果您不想使用jQuery,则可以使用本机javascript代码:
document.getElementById('myLink').addEventListener('click',function(e){
// your show_create_msg code here
});
希望能有所帮助
如果您不想更改html源,请从element的href
属性获取functoin名称,并将其设置为onclick
属性。
var fn = $("a").attr("href").replace("#table:", ""); $("a").attr("onclick", fn) function show_create_msg(){ console.log("function called"); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#table:show_create_msg();">Table</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.