gpt4 book ai didi

javascript - Jquery 每个循环不工作

转载 作者:行者123 更新时间:2023-11-30 09:10:04 25 4
gpt4 key购买 nike

我是 jquery 的新手,但我正在尝试在我的项目中使用它。我试图遍历 #rate_box 内的所有链接并向它们添加点击事件。这个点击事件会将一些数据发布到外部 php 脚本,然后它应该解除绑定(bind)所有链接上的点击事件(这样人们就不能快速连续评价两次。)然后它应该将从 php 脚本接收到的数据放入一个名为 #status 的 span 标签。

但是我的代码甚至没有执行 alert("Index: "+i)。我是否正确绑定(bind)了它?

<script type="text/javascript">
$(document).ready(function(){
$('#rate_box a').each(function(i) {
$(this).click(function() {
alert("Index: "+i);
$.post("../includes/process/rating.php", {id: "<?php $game_id ?>", type: "game", rating: i+1},
function(data) {
$('#rate_box a').each(function(i) {
$(this).unbind('click');
}
$('#status').html(data).fadeIn("normal");
});
});
});
});
</script>

最佳答案

您不需要循环遍历每个单独绑定(bind)处理程序的链接,您可以这样做:

// bind click handler to all <a> tags inside #rate_box
$('#rate_box a').click(function() {

});

解除绑定(bind)也是如此:

$('#rate_box a').unbind('click');

就您的代码而言,它可能没有执行,因为您在取消绑定(bind)元素标签时没有关闭内部 each,因此它是无效的 javascript:

$('#rate_box a').each(function(i) {
$(this).unbind('click');
} // <- missing closing ");"

你真的应该使用像 Firebug 或 Firebug Lite 这样的工具来调试你的 javascript,尽管像上面这样的东西在大多数浏览器中只会给你一个 Javascript 错误。

编辑 如果你想在点击时找到当前链接的索引,你可以这样做:

var links = $('#rate_box a');
$(links).click(function() {
// this is to stop successive clicks on ratings,
// although the server should still validate to make
// sure only one rating is sent per game
if($(this).hasClass('inactive_for_click')) return false;
$(links).addClass('inactive_for_click');
// get the index of the link relative to the rest, add 1
var index = $(links).index(this) + 1;
$.post("../includes/process/rating.php", {
id: "<?php $game_id ?>",
type: "game",
rating: index
}, function(data) {
$('#status').html(data).fadeIn("normal");
// unbind links to disable further voting
$(links).unbind('click');
});
});

关于javascript - Jquery 每个循环不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/703983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com