简体   繁体   中英

Can I make a link point to a javascript function?

My code is:

<input class="button"  type="button" value="Mark" onClick="doCheck('mark');" \>

I want to make it using an

<a>

link. Is it possible to do this? I only know how linking to another page.

Use Like that

<a class="button"  href="javascript:void(0)" onClick="doCheck('mark');" >Mark</a>

or this way

<a class="button"  href="javascript:doCheck('mark')" >Mark</a>

< a href='javascript:void(null);' onclick='doCheck()' > Test </a>

<a onClick="doCheck('mark');"> Mark </a>

You can attach click handlers to any DOM element that is visible on the page. I would seperately recommend seperation of markup and javascript.

So something like.

<a id="mark">

...

<script type="text/javascript">

$(function() {
     $("#mark").click(function() {
         doCheck("mark");
     });
});

</script>

Would be preferable. In this case $ is jQuery . A pure javascript solution is possible but that has a lot of boilerplate code that hides the point.

This code example will execute the JavaScript without following the link:

<a href="#" onclick="doCheck('mark'); return false;">Mark</a>

If you want to follow the link, drop the return false; part:

<a href="somewhere.html" onclick="doCheck('mark');">Mark</a>

You can use the onClick attribute on any html element. So use it in your a tag or in your img tag.

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