[英]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.