【发布时间】:2014-03-06 21:32:52
【问题描述】:
我有一个被证明是困难的问题。我有一个论坛,对一个问题有多个回复,从数据库中提取并使用 foreach 循环(PHP)显示。我想要一个“编辑您的响应”功能并有一个 jquery 功能,它将“显示”一个 HTML 块,其中包括每个响应下方的输入。问题是,当我在一个响应上选择编辑按钮时,它会在每个响应下激活 HRML 块,因为它针对“theDiv”类。是否有可能有一个只能选择一个的 jquery 函数......即,不知何故,foreach 循环中的每个响应都有一个动态创建的唯一类,jquery 函数可以针对该类?真的很难看到如何做到这一点......
<html>
<head>
<style type="text/css">
.theDiv{
display:none;
}
</style>
<link href="styles/threads_page.css" media="all" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(function() {
$(".show").click(function() {
$(".theDiv").show("normal");
});
$(".hide").click(function() {
$(".theDiv").hide("normal");
});
});
</script>
</head>
<body>
<?php foreach($responses as $response):?>
<h3><?php echo $response->author . "<br/>";
echo $response->content;
echo "<div class=\"theDiv\">
<form action=\"question_gallery.php\" method=\"post\" class=\"form\">
<table>
<tr>
<td>
Edit your response:
<input class=\"question_field\" name=\"question\"/>
</td>
</tr>
</table>
</form>
</div>
<table>
<tr>
<td>
<button class=\"show\">Edit response</button>
</td>
<td>
<button class=\"hide\">Close</button>
</td>
</tr>
</table>
";} ?>
<?php endforeach; ?>
</body>
</html>
【问题讨论】:
-
使用
$(this)仅定位被点击的元素。 -
以
this开头,遍历DOM到你想要的元素。 api.jquery.com/category/traversing