我发现某人的投票系统使用jquery,并想将其合并到我的网站。不幸的是,我希望它检测用户是否已经投票,并根据此显示vote-up或vote-down按钮(和链接)。
它工作得很好-除了当我动态改变投票按钮,即。如果我投票否决了一个项目,我将图标更改为投票,但当我单击投票图标时,超链接操作不会被触发。我需要做些什么来"重新连接"吗?注意:我只是在vote-down, vote-up上实现了这个逻辑,我还没有改变,所以它目前清除了投票按钮。这将被修复。
如果这是重要的知道-这是在一个。net/mvc应用程序。
<script type="text/javascript">
$(document).ready(function() {
function onChange(newPageValue) {
UpdateStories(newPageValue);
}
$(function() {
$("a.vote_up").click(function() {
//get the id
var theId = $(this).attr('id').replace('vote_', '');
// show the spinner
$(this).parent().html("<img src='content/images/spinner.gif'/>");
//fadeout the vote-count
$("span#votes_count_" + theId).fadeOut("fast");
//the main ajax request
$.ajax({
type: "POST",
data: { action: "vote_up", id: $(this).attr("id")},
url: "@Url.Action("ProcessVote", "Vote")",
success: function(msg) {
$("span#votes_count_" + theId).html(msg);
// fadein the vote count
$("span#votes_count_" + theId).fadeIn();
// remove the spinner
$("span#vote_buttons_" + theId).html('');
}
});
});
});
$(function() {
$("a.vote_down").click(function() {
//get the id
var theId = $(this).attr('id').replace('vote_', '');
// show the spinner
$(this).parent().html("<img src='content/images/spinner.gif'/>");
//fadeout the vote-count
$("span#votes_count_" + theId).fadeOut("fast");
//the main ajax request
$.ajax({
type: "POST",
data: { action: "vote_down", id: $(this).attr("id")},
url: "@Url.Action("ProcessVote", "Vote")",
success: function(msg) {
$("span#votes_count_" + theId).html(msg);
// fadein the vote count
$("span#votes_count_" + theId).fadeIn();
// remove the spinner
var votelink = "<a href='javascript:;' class='vote_up' id='vote_" + theId + "'></a>";
$("span#vote_buttons_" + theId).html(votelink);
}
});
});
});
});
</script>
html/mvc视图中引用的部分是:
@foreach (var story in Model.UserStories)
{
<tr>
<td>@story["FormattedID"]
</td>
<td>@story["Name"]
</td>
<td>@Html.Raw(story["Description"])
</td>
<td>@story["TaskEstimateTotal"]
</td>
<td>
<span class='votes_count' id='votes_count_@story["FormattedID"]'>@story["VoteCount"]</span> votes
<br/>
<span class='vote_buttons' id='vote_buttons_@story["FormattedID"]'>
@if (story["Voted"])
{
<a href='javascript:;' class='vote_down' id='vote_@story["FormattedID"]'></a>
}
else
{
<a href='javascript:;' class='vote_up' id='vote_@story["FormattedID"]'></a>
}
</span>
</td>
</tr>
}
所以我的逻辑工作正常-除了当我动态地把投票按钮到html占位符,然后它不再触发它需要的事件。
编辑-我确实尝试将函数移动到文档准备函数之外,但这也不能解决问题。
这只会将点击事件注册为页面上的当前元素
$("a.vote_up").click(function() {
如果你想确保动态元素被覆盖,你应该做的是使用on
。
$("body").on("click",'a.vote_up',function(){
,它将把此事件委托给所有当前和未来的锚元素,类为vote_up。