Javascript 如何从html中的href标签调用javascript函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8149647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:53:10  来源:igfitidea点击:

How to call a javascript Function from href tag in html?

phpjavascriptjavascript-events

提问by ScoRpion

How to call a JavaScript Function from href tag in html? I have created few tabs . I want when user clicks on any tab the href along with JavaScript function should get called. How can I do it?

如何从html中的href标签调用JavaScript函数?我创建了几个选项卡。我希望当用户单击任何选项卡时,应该调用 href 和 JavaScript 函数。我该怎么做?

<?php if($order == 1){ ?>
<li class="cat-one"><a href= "javascript:loadProducts($categoryId)" > <?php echo $categoryName ?> </a></li>
<?php } ?>

This is my Javascript

这是我的 JavaScript

<script type="javascript" >
function loadProducts($categoryId)
{
    alert("Hello World!");
    return false;
}

</script>

回答by Ranhiru Jude Cooray

In the href tag, without specifying a link, specify your javascript function name.

在 href 标签中,不指定链接,指定您的 javascript 函数名称。

For example

例如

<a href='javascript:myFunction()'> Click Me! <a/>

回答by red-X

Don't use the href, use the onclickattribute for this

不要使用hrefonclick为此使用属性

<a href="http://www.example.com" onclick="return confirm('are you sure?')">test</a>

see this example

这个例子

EDIT(since code added in question): this should call your JS function:

编辑(因为添加了有问题的代码):这应该调用您的 JS 函数:

<?php if($order == 1){ ?>
  <li class="cat-one">
    <a href="javascript:void(0)" onclick="loadProducts(<?php echo $categoryId ?>)"> 
      <?php echo $categoryName ?> 
    </a>
  </li>
<?php } ?>

回答by Anish

Try this

尝试这个

  <html>
    <body>
    <script type= "text/javascript">
    function loadProducts(catid){
        alert(""Hello World!"+catid);
        return false;
    }
    </script>


    <?php if($order == 1){ ?>
    <li class="cat-one">
        <a href="javascript:void(0)" onclick="loadProducts(<?php echo $categoryId ?>)"><?php echo $categoryName ?> </a>
    </li> 

    </body>
    </html>

回答by sunny

This should solve your purpose:

这应该可以解决您的目的:

<a href="javascript:void(0);" onclick="yourFunction();">Link to Click</a> 

回答by MajklRS

If you have jquery library you can call with class:

如果你有 jquery 库,你可以用类调用:

$( ".loadProducts" ).click(function( event ) {
      // Default action of the event will not be triggered.
      event.preventDefault();
      // Get category ID
      var categoryId = $(this).attr('data-categoryid');
      // TODO
      alert("Hello World!");
      return false;
});

For:

为了:

<li class="cat-one"><a href="#" class="loadProducts" data-categoryid="<?php echo $categoryId;?>" > <?php echo $categoryName ?> </a></li>