我有一个博客,从一些SQL数据库中获取数据。我有一个问题,从foreach循环中获得正确的数据,我不知道为什么。我会尽力解释的。
对于每个图像,都有一个文本区域,用户可以在其中输入评论。对于每个注释,我都必须发送相应的id(ajax)以添加到数据库中。
foreach($db->query("SELECT id, image FROM news") as $row)
{
<a href='images/news/{$row['image']}'><img src='images/news/{$row['image']}'/></a>";
<div class="save_comment">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>
<input type="text" class="_comment_id" name="id" value="<?php print_r($row['id'] );?>" />
Comment:
<textarea id="_comment_text" class="comment_area" name="comment_area" maxlength="400" cols="80" rows="8" ></textarea>
</td>
</tr>
<tr>
<td>
<a class="post_comment" href=".popupContainer">Post Comment</a>
</td>
</tr>
</table>
</div>
}
点击"PostComment",以下js脚本将被初始化。。。。
<script type="text/javascript">
jQuery(document).ready(function() {
$(".post_comment").leanModal({top : 200, overlay : 0.6, closeButton: ".modal_close" });
$(function(){
jQuery('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
jQuery('.tabs ' + currentAttrValue).show().siblings().hide();
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
});
});
</script>
并显示一个弹出容器(div with class.popupContainer),用户可以在其中最终提交他们的评论。
<div class="popupContainer" style="display:none;">
Your Name: <input type="text" class="_user_name" />
Email:<input type="text" class="_comment_email" />
<input type='button' class='_submit_comment' value='Speichern' >
</div>
通过提交此注释,以下脚本将被初始化,数据将通过ajax发送。
<script type="text/javascript">
$("._submit_comment").click(function(){
var parentObj = $(this).closest('.save_comment');
var _comment_id = parentObj.find('._comment_id').val(); -> I don't get the correct id
问题就从这里开始了。我只从foreach循环中获得第一个id,但我需要为每个评论获得相应的id。有人能帮我解决这个问题吗?非常感谢。其他
此部件错误IMHO:
$(this).closest('.save_comment');
当你点击"Post Comment"时,你应该设置一个JS变量,id可以存储在链接中,比如:
<a class="post_comment" href=".popupContainer" data-idcomment="<?php print($row['id'] );?>">Post Comment</a>
和
var _comment_id = null;
jQuery('.tabs .tab-links a').on('click', function(e) {
_comment_id = jQuery(this).data('idcomment');
var currentAttrValue = jQuery(this).attr('href');
jQuery('.tabs ' + currentAttrValue).show().siblings().hide();
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
});
});
然后您可以使用_comment_id
进行ajax调用