简体   繁体   中英

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(); here is my code

<a  href="#table:show_create_msg();">Table</a>
function show_create_msg()
{
   alert("error");
}

Add onclick event and prevent the click event, then its doesn't load the page when you click the link.

<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

<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:

<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.

I will show you how to do it in a more proper way (using "onclick" inline the element is not a good practice)

Here's an example:

HTML

<a id="myLink" href="#table">Table</a>

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:

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.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM