javascript - 识别点击的链接并将 id 传递给函数

标签 javascript php html

我想在每次点击链接时调用一个函数。在这个函数中,我将调用相应的页面。如果不为每个链接创建一个函数,我如何识别被点击的链接?这是 javascript 和 php 的混合体,展示了我想怎么做。

<div>
  <ul><li><a id="address" href="clicked">address</a></li></ul>
  <ul><li><a id="about" href="clicked">about</a></li></ul>
</div>

<?php
    function clicked() {
       $theaddress = $("#address").isClicked(); //looking at a function like isClicked
       $theabout=  $("#about").isClicked(); //do the same thing in case the function exists

       if ($theaddress) {
         //call the address page
       }
       else if ($theabout) {
         // call the about page
       }
     }
?>

我想知道这是否真的可能。我知道我可以为每个链接设置一个功能,但对我来说这看起来功能太多了。到目前为止,这就是我得到的from stackoverflow

最佳答案

您可以使用 onClick鼠标事件。

内联:
<a href=# onClick="window.location.href = 'http://www.google.com'">HERE</a>

调用函数(内联 url):

<a href=# onClick="redirect('http://www.google.com')">HERE</a>

<script>
    function redirect(key) {     
    window.location.href = key;
    }
</script> 

调用一个函数(url inside):

<a href=# onClick="redirect('a1')">HERE</a>  
<a href=# onClick="redirect('a2')">HERE</a>

<script>
    function redirect(key) {
    if (key == "a1") {  
    window.location.href = 'http://www.google.com';
    } else if (key == "a2") {
    window.location.href = 'http://images.google.com';
    } 
    }
</script>

关于javascript - 识别点击的链接并将 id 传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35825720/

相关文章:

php - 字段不在实体中的 Symfony2 表单

CSS3 和菜单项突出显示

javascript - NodeJS "readline"模块不输出提示

php - PHP中如何获取最后插入的id

php - 如何使用 dompdf 生成目录?

html - WebRTC - 禁用所有音频处理

html - 使用 CSS 将 35 度徽章剪切成图像

JavaScript 和 HTML : in two separate files or in a single HTML file?

javascript - 重复 DIV 上的按钮只影响那个 DIV?

javascript - 在 Javascript 中使用 Java 库