我正在尝试用jquery在一个有多个表单的php页面上定位一个特定的表单元素。表单是动态生成的,并包含在while循环中。表单是位于每个页面包含三个帖子的单个帖子下的评论表单。
因为表单和表单字段是动态生成的,所以我需要使用类名,而不是id。然而,为了区分每个表单,我可以将id附加到每个表单以区分它们,但id将是一个基于post id的整数。下面是我的表单结构:
<div class="cform" id="'.$id.'">
<form action="" method="" enctype="" class="vidcomfrm" name="'.$id.'">
<h3>Add Comment to '.$title.' video</h3>
<div class="row">
<label><span class="label">Your Name:</span>
<input name="name" class="vname" id="'.$id.'" type="text" value=""/>
</label>
<label><span style="margin-left:.5em; width:75px;">Email:</span>
<input name="email" class="vemail" id="'.$id.'" type="text" value="" />
</label>
</div>
<div class="row">
<label><span class="label">Comments:</span>
<textarea name="comments_body" class="vcomments" id="'.$id.'" rows="2" class="formw" /></textarea>
</textarea>
</label>
</div>
<div class="row">
<input type="hidden" name="vid" value="'.$id.'" />
</div>
<input name="submit" type="submit" value="Add Comment" class="comment_submit" id="'.$id.'" />
</form>
<ul class="response" id="'.$id.'" /><!--success or failure message goes here -->
</div><!--/cform div-->下面是我使用的Jquery代码
$(function() {
$('form.vidcomfrm').submit(function(event) {
event.preventDefault(); // stop the form submitting
$('div.cform').append('<img src="../images/pageElements/ajax-loader.gif" class="loaderIcon" alt="Loading..."/>');//this will simulate processing by loading an animated gif
var data = $(this).serialize(); // $(this) represents the form object
$.post('../Scripts/processVidcoms.php', data, function(results) {
$('div.cform img.loaderIcon').fadeOut(1000);//fade out processing simulation image
$('ul.response').html(results);//display succcess or failure errors.
//clear the form data
$('.vname').val('');
$('.vemail').val('');
$('.vcomments').val('');
});
});
});当用户提交表单时,submit按钮的默认操作被阻止,processVidcoms.php通过执行表单验证、将注释插入到comments表并返回成功消息或失败消息来接管此操作。这已经完美地发挥了作用。
问题出在响应结果和ajax-loader.gif上。当用户单击add comment按钮时,ajax-loader.gif和响应将显示在每个表单下!我只想让响应在用户单击的表单下返回。我已经尝试了所有的方式,使用$(this)和指定变量,但我所能做到的最好的就是上面的内容。
使用上面的jquery代码开始,我如何修改它才能针对特定的表单?
谢谢!
发布于 2010-11-14 03:43:29
$(this)将提供用户submitted.$(this).parent()为该元素的父元素提供的格式(在本例中,带有cform).$(this).parent().find()类的周围的div将只返回与所提供的CSS样式选择器匹配的div的子项、孙项等项。因此,对于微调器的淡入/淡出:
// Fade in
$(this).parent().append('<img src="../images/pageElements/ajax-loader.gif" class="loaderIcon" alt="Loading..."/>');
// Fade out
$(this).parent().find('img.loaderIcon').fadeOut(1000);要显示响应,请执行以下操作:
$(this).parent().find('ul.response').html(results);对于表单域的重置:
$(this).parent().find('.vname').val('');
$(this).parent().find('.vemail').val('');
$(this).parent().find('.vcomments').val('');编辑:修复了上述代码的一个问题。.children只下了一个级别,所以我改正了代码,改为使用.find。
发布于 2010-11-14 03:37:55
$(this).parent()应该会给你一个你需要的<div>的引用(而不是$('div.cform'))。
https://stackoverflow.com/questions/4174278
复制相似问题