我正在尝试为我的网站制作一个“喜欢”的系统。我写了这段代码:
<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更改后运行代码?
答案 0 :(得分:1)
如果你的所有跨度都具有相同的id =“like”,那么只有一个会起作用,其余的将被忽略... ids必须是唯一的..
也许试试......
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');