在我的php中我在while循环中有这样的代码......
$result = mysql_query("SELECT * FROM wallpost ORDER BY wallpostid DESC");
while($row = mysql_fetch_assoc($result)){
$rate = "<div class=\"example-".$id." \" data-postid=\"".$id."\"></div></br>Post id: <span class=\"example-rating-".$id."\">".$id."</span>";
}
jquery是......
$(document).ready(function() {
$('[class^="example-"]').not('[class^="example-rating-"]').ratings(3).bind('ratingchanged', function (event, data) {
var child = $(this).find('[class^="example-rating-"]');
child.text(data.rating);
$.post('count.php', {
rate: data.rating,
wallpostid: jQuery(this).data("postid")
}, function (data) {
alert(data);
});
});
表示值A我得到空值,但是如果我替换
var a = $('.example-rating-50').html(); //let say the wallpostid is 50
它只能将值50传递给count.php 如果现在让我说我有2个wallpostid,它是22和50(循环时循环) 如果我评价wallpostid是22然后我想从PHP传递$ id = 22的值到jquery和$ .post到count.php。如果我对wallpostid = 50进行评分,请执行此操作。
答案 0 :(得分:4)
闭包变量i
由于你在回调中使用i
,它将具有来自循环的最后一个值102,这就是它失败的原因
$(document).ready(function () {
for (var i = 1; i < 101; i++) {
(function(idx){
$('.example-' + idx + '').ratings(3).bind('ratingchanged', function (event, data) {
$('.example-rating-' + idx + '').text(data.rating);
var a = $('.example-rating-' + idx + '').html();
$.post('count.php', {
rate: data.rating,
wallpostid: a
}, function (data) {
alert(data);
});
});
})(i)
}
});
更好的解决方案可能是
$rate = "<div class=\"examples example-".$id." \" data-idx=\"".$id"\"></div></br>Post id: <span class=\"example-rating-".$id."\">".$id."</span>";
然后
$(document).ready(function () {
$('.examples').ratings(3).bind('ratingchanged', function (event, data) {
var i = $(this).data('idx')
var a = $('.example-rating-' + i + '').text(data.rating);
$.post('count.php', {
rate: data.rating,
wallpostid: data.rating
}, function (data) {
alert(data);
});
});
});
答案 1 :(得分:0)
你在javascript中不需要for循环,有选择器可以处理这个,例如class^=
<强> PHP 强>
$rate = "<div class=\"example-".$id." \" data-postid=\"".$id."\"></div></br>Post id: <span class=\"example-rating-".$id."\">".$id."</span>";
<强> JS 强>
//Find elements that have class starting with 'example-' but Not example-rating-
$('[class^="example-"]').not('[class^="example-rating-"]').ratings(3).bind('ratingchanged', function (event, data) {
//Find Child element that has class starting with 'example-rating-'
var child = $(this).find('[class^="example-rating-"]');
child.text(data.rating);
$.post('count.php', {
rate: data.rating,
wallpostid: jQuery(this).data("postid")
}, function (data) {
alert(data);
});
});
答案 2 :(得分:0)
我不想动态构建元素选择器。
var $examples = $('[class^=example-]:not([class^=example-rating])');
var $ratings = $('[class^=example-rating]');
$examples.ratings(3).bind('ratingchanged', function (event, data) {
var index = $examples.index(this);
var $rating = $ratings.eq(index);
$rating.text(data.rating);
var a = $rating.attr('class').split('-')[2];
$.post('count.php', {
rate: data.rating,
wallpostid: a
}, function (data) {
alert(data);
});
});