[英]how to call a javascript function if the href has the hash tag id
I want to call the javacsript function on href if the href has the hash tag id.I need the #table as i am using bootstrap tabs so cannot use javasript:show_create_msg(); 如果href具有哈希标签ID,我想在href上调用javacsript函数。我需要#table,因为我正在使用引导程序选项卡,因此无法使用javasript:show_create_msg(); here is my code
这是我的代码
<a href="#table:show_create_msg();">Table</a>
function show_create_msg()
{
alert("error");
}
Add
onclick
event andprevent
the click event, then its doesn't load the page when you click the link.添加
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>
incase you need to find hash
http://example.com#table
如果您需要找到哈希
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>
Add onclick
event to this link and then write a JavaScript function that does something: 将
onclick
事件添加到此链接,然后编写一个执行以下操作的JavaScript函数:
<a href="#" onclick="show_create_msg();">Table</a>
<script>
function show_create_msg()
{
// Do something;
}
</script>
You can give your element an id, and attach a click event to it. 您可以为您的元素指定一个ID,并为其添加click事件。
I will show you how to do it in a more proper way (using "onclick" inline the element is not a good practice) 我将向您展示如何以更适当的方式进行操作(内联使用“ onclick”元素不是一个好习惯)
Here's an example: 这是一个例子:
HTML HTML
<a id="myLink" href="#table">Table</a>
jQuery jQuery的
$('#myLink').on('click',function(){
show_create_msg();
});
or even better: 甚至更好:
$('#myLink').on('click',function(){
// your show_create_msg code here
});
If you want to prevent the default link behaviour: 如果要防止默认链接行为:
$('#myLink').on('click',function(e){
e.preventDefault();
// your show_create_msg code here
});
If you want to trigger the code only on specific hash value: 如果只想在特定的哈希值上触发代码:
$('#myLink').on('click',function(e){
var hash = window.location.hash;
if(hash=='#table'){
// your show_create_msg code here
}
});
If you don't want to use jQuery you can use native javascript code: 如果您不想使用jQuery,则可以使用本机javascript代码:
document.getElementById('myLink').addEventListener('click',function(e){
// your show_create_msg code here
});
Hope it helps a bit 希望能有所帮助
If you don't want to change your html source, get functoin name from href
attribute of element and set it to onclick
attribute of it. 如果您不想更改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.