我想为我的网站做一个"喜欢"系统。我写了下面的代码:
<a href='website.php#$id' ><span class='glyphicon glyphicon-thumbs-up like' id='like' ></span></a>
JQuery: $(document).ready(function() {
$(".like").click(function(event) {
var id = (window.location.hash);
id = id.replace("#", "");
alert(id);
});
});
它在大多数情况下都有效,但如果我"喜欢"一个帖子,然后是另一个帖子,它会重新输入最后一个帖子的id。如何在URL更改后运行代码?
如果所有的span都有相同的id="like",那么只有一个可以工作,其余的将被忽略…id必须唯一。
也许试试…
HTML..
<a href="website.php#$id"><span class="like other-classes"></span></a>
JS
$('.like').on('click',function(){
var id = (window.location.hash);
id = id.replace("#", "");
alert(id);
});
或者……
HTML...
<a href="" id="$id" class="like"><span class="glph-classes"></span></a>
JS...
$('.like').on('click',function(e){
e.preventDefault();
var id = $(this).attr('id');
alert(id);
});
注意:同样,id必须是唯一的…如果这不可能……将以上内容更改为
<a href="" data-id="$id">....</a>
and the js will change to..
var id = $(this).attr('data-id');