将点击事件绑定到我页面上的锚定标签 [英] bind click event to anchor tags on my page
问题描述
以下是我的javascript文件代码. Script.js
Below is my javascript file code. Script.js
$(document).ready(function(){
$("#").click(function(){
alert("Hello!");
});
这是我的php代码.
<html>
<head>
Some codes are here
</head>
<body>
Some php codes are here to get value from database
<script src="script.js"></script>
<span><a href="#" class="vote" id="<?php echo $cid; ?>" name="up"><i class="fa fa-thumbs-up"></i></a> <?php echo $up; ?> </span>
<span><a href="#" class="vote" id="<?php echo $cid; ?>" name="down"><i class="fa fa-thumbs-down"></i></a> <?php echo $down; ?> </span>
<span><a href="#" class="vote" id="<?php echo $cid; ?>" name="favorite"><i class="fa fa-star-o"></i></a> <?php echo $fav; ?> </span>
</body>
</html>
由于我的设计原因,我正在体内调用脚本文件.我不能在头部称呼它.
I am calling script file in body due to my design. I can't call it in head section.
问题是当我单击与#(上,下,最爱)相对应的以上链接时.我需要索引文件.我正在警报框中测试Hello.但这不起作用.
Issue is when i click on above link corresponding to # (up,down, fav). It take me to index file. I am testing Hello in alert box. But it is not working.
任何建议我想念的东西.
Any advice what i am missing.
推荐答案
$("#")
中的#
表示,并且id
应该紧随其后.就像您的元素的ID为"myElement"一样,您会写$("#myElement")
.
The #
in $("#")
means and id
should follow. Like if your element's id were "myElement" you would write $("#myElement")
.
但是,由于您不知道id的使用时间,id使用了已经具有的vote
类,例如$(".vote").click....
But, since you dont know your ids adead of time, id use the vote
class you already have instead like $(".vote").click....
$(document).ready(function() {
$(".vote").click(function(event) {
event.preventDefault();
alert("Hello! My id is: " + this.id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<span><a href="#" class="vote" id="someId1" name="up"><i class="fa fa-thumbs-up"></i>Some sontent</a></span>
<span><a href="#" class="vote" id="someId2" name="down"><i class="fa fa-thumbs-down"></i>Some sontent</a> </span>
<span><a href="#" class="vote" id="someId3" name="favorite"><i class="fa fa-star-o"></i>Some sontent </a> </span>
这篇关于将点击事件绑定到我页面上的锚定标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!