我想在每次点击链接时调用一个函数。在这个函数中,我将调用相应的页面。如果不为每个链接创建一个函数,我如何识别被点击的链接?这是 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/